在wp_nav_menu中的li元素中添加类 [英] Adding class to li elements in wp_nav_menu
问题描述
我在wordpress中的wp_nav_menu有问题.我要构建李元素的结构,所有元素都将具有"menu-li"类.但这对我不起作用.我在function.php文件中有此文件:
I have problem with wp_nav_menu in wordpress. I want to make structure of Li elements, where all of them will have class "menu-li". But It doesn't work for me. I have this in function.php file:
register_nav_menus(
array(
'primary-menu' => __( 'Primary Menu' ),
'secondary-menu' => __( 'Secondary Menu' )
));
然后我在Wordpress管理面板中创建了菜单,现在我想将菜单添加到主题中.
Then I created Menu in Wordpress admin panel and now I want to add my menu to my theme.
<?php
$defaults = array(
'theme_location' => 'primary-menu',
'menu' => '',
'container' => '',
'container_class' => '',
'container_id' => '',
'menu_class' => 'menu-li',
'menu_id' => '',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' => '',
'after' => '',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul>%3$s</ul>',
'depth' => 0,
'walker' => ''
);
wp_nav_menu( $defaults );
?>
它在ul中将所有elemnet显示为li,但没有类"menu-li".如何将其添加到所有li元素中?
It displays all elemnet as li in ul but there is no class "menu-li". How can I add it to all li elements?
推荐答案
menu_class参数> wp_nav_menu()
控制添加到<ul>
包装器元素中的类,而不是单个<li>
的类.要将类添加到菜单项,您要使用 nav_menu_css_class
过滤器.
The menu_class
parameter of wp_nav_menu()
controls the class added to the <ul>
wrapper element, rather than the individual <li>
's. To add classes to the menu items, you want to use the nav_menu_css_class
filter.
这是它的工作方式(将此添加到主题的functions.php
文件中):
Here's how it works (add this to your theme's functions.php
file):
add_filter ( 'nav_menu_css_class', 'so_37823371_menu_item_class', 10, 4 );
function so_37823371_menu_item_class ( $classes, $item, $args, $depth ){
$classes[] = 'menu-li';
return $classes;
}
这会将menu-li
类添加到每个菜单项.
This will add the menu-li
class to every menu item.
如果愿意,您还可以根据传递给此过滤器的$item
,$args
等有条件地执行此操作.
You can also do this conditionally based on the $item
, $args
etc. passed to this filter if you like.
这篇关于在wp_nav_menu中的li元素中添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!