如何在WordPress中向菜单项添加自定义类。下面是我的代码,它不起作用

时间:2018-05-20 11:04:19

标签: wordpress wordpress-theming

的header.php

/*Render menu*/
<div class="main-nav">
   <?php wp_nav_menu( 
     array( 
     'theme_location' => 'header-menu',
     'container' => 'ul',
     'menu_class' => 'nav'
     ) 
   ); 
   ?>
</div>

的functions.php

/*Register menu*/
function register_main_menu(){
 register_nav_menus(array(
    'Primary' => __('Header Menu'),
    'Footer' => __('Footer Menu')
 ));
}
add_action('after_setup_theme', 'register_main_menu');

/*Custom menu class*/
function add_class_to_li($classes, $item){
  $classes[] = "nav-item";
  return $classes;
}
add_filter('nav_menu_css_class','add_class_to_li', 10, 4);

这不会将'nav-item'类添加到'li'。有什么我需要更新。

1 个答案:

答案 0 :(得分:0)

您的theme_location应该与您在functions.php文件中的名称完全相同。所以你的读者菜单将是:

/*Render menu*/
<div class="main-nav">
   <?php wp_nav_menu( 
     array( 
     'theme_location' => 'Primary',  //this will be Primary, not header-menu
     'container' => 'ul',
     'menu_class' => 'nav'
     ) 
   ); 
   ?>
</div>