向 wp_nav_menu 中的 li 元素添加类 [英] Adding class to li elements in wp_nav_menu
问题描述
我在 wordpress 中遇到 wp_nav_menu 问题.我想制作 Li 元素的结构,其中所有元素都有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 参数rel="noreferrer">wp_nav_menu()
控制添加到
包装元素的类,而不是单独的
的.要将类添加到菜单项,您需要使用 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屋!