在 wordpress 主题中,如何向<a>导航中的项目添加类?



我目前正在制作一个wordpress主题,我在使用wp_nav_menu()向菜单中的项目添加类时遇到了麻烦。

非wordpress版本的菜单是这样的:

<div class="collapse navbar-collapse" id="navbarsExampleDefault">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link page-scroll" href="#header">HOME <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link page-scroll" href="#features">FEATURES</a>
</li>
<li class="nav-item">
<a class="nav-link page-scroll" href="#details">DETAILS</a>
</li>                
</ul>
</div>

我可以添加"nav-item"通过使用附加参数并在functions.php:

中设置过滤器,可以将li项转换为li项,而不会出现任何问题。header。php:

<?php
wp_nav_menu( 
array(
"theme_location" => "top-menu",
"menu_class" => "navbar-nav ml-auto",
"container" => "div",
"container-class" => "collapse navbar-collapse",
"container-id" => "navbarDefault",
"fallback_cb" => false,
"add_li_class" => "nav-item",
)
);
?>

显然也
function add_additional_class_on_li($classes, $item, $args) {
if(isset($args->add_li_class)) {
$classes[] = $args->add_li_class;
}
return $classes;
}
add_filter('nav_menu_css_class', 'add_additional_class_on_li', 1, 3);```

I've tried creating a custom walker but that just crashes the entire site every time I try to add a new site to the nav menu.

稍微修改一下函数

function add_additional_class_on_li( $classes, $item ) {
$classes[] = 'nav-item';
return $classes;
}
add_filter( 'nav_menu_css_class', 'add_additional_class_on_li', 10, 2 );

可选择针对特定菜单:

function add_additional_class_on_li( $classes, $item, $args ) {
if ( 'top-menu' === $args->theme_location ) {
$classes[] = 'nav-item';
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'add_additional_class_on_li', 10, 2 );

也可以使用nav_menu_link_attributes钩子来添加链接类:

function add_additional_class_on_nav_link( $atts, $item, $args ) {
if( $args->theme_location == 'top-menu' ) {
$atts['class'] = 'nav-link page-scroll';
}
return $atts;
}
add_filter( 'nav_menu_link_attributes', 'add_additional_class_on_nav_link', 10, 3 );

相关内容

  • 没有找到相关文章

最新更新