How to add class to link in wp_nav_menu?

后端 未结 4 636
予麋鹿
予麋鹿 2020-12-05 07:12

I am trying to out a wp menu without ul and li and have a class added to the element.

I have tried adding this in my function.php

function add_menuc         


        
4条回答
  •  孤城傲影
    2020-12-05 07:49

    Taking a hint from this answer which I found was the most concise about adding classes to the list items of the menus, I used nav_menu_link_attributes filter which does work well for adding classes.

    In your functions.php, add:

    function add_menu_link_class( $atts, $item, $args ) {
      if (property_exists($args, 'link_class')) {
        $atts['class'] = $args->link_class;
      }
      return $atts;
    }
    add_filter( 'nav_menu_link_attributes', 'add_menu_link_class', 1, 3 );
    

    Optionally, you may want to add the option to add classes to list items:

    function add_menu_list_item_class($classes, $item, $args) {
      if (property_exists($args, 'list_item_class')) {
          $classes[] = $args->list_item_class;
      }
      return $classes;
    }
    add_filter('nav_menu_css_class', 'add_menu_list_item_class', 1, 3);
    

    Now, in your template, to build a menu you just add two new arguments, e.g.:

    wp_nav_menu([
        'theme_location'=> 'primary_navigation',
        'menu_class'    => 'navbar-nav ml-auto flex-nowrap',
        'list_item_class'  => 'nav-item',
        'link_class'   => 'nav-link m-2 menu-item nav-active'
    ]);
    

    Works well with themes with multiple menus which have different appearance.

提交回复
热议问题