1

How can I filter the presentation of menu items to add classes to anchors?

I already have the code below, in which I leverage the per-item "Description" field set in WordPress admin's Menus creator. But it's a bit of a hack, and it doesn't leverage the "CSS Classes (optional)" field available in the Menus creator.

  • Other methods I have seen filter to add classes to <li>. Instead, I want to add classes to <a> - but not to replace the classes WordPress itself already applies to <a>.
  • I want to know how to take those classes from the Menus creator field "CSS Classes (optional)".
  • But I would also like to hard-set the additional classes in code, not from the "CSS Classes (optional)" field.

      /**
       * ==============================================================================
       *                       INSERT CLASSES IN TO NAV ITEMS
       * ==============================================================================
       */
    
      /**
       * Store class names in menu description field.
       * Used, eg. to make a nav item hidden
       */
    
      /**
       * Descriptions on Header Menu
       * @author Bill Erickson
       * @link http://www.billerickson.net/code/add-description-to-wordpress-menu-items/
       *
       * @param string $item_output, HTML outputp for the menu item
       * @param object $item, menu item object
       * @param int $depth, depth in menu structure
       * @param object $args, arguments passed to wp_nav_menu()
       * @return string $item_output
       */
    
      // Use menu item description field to store class name for output to link
      function be_header_menu_desc( $item_output, $item, $depth, $args ) {
    
        // Only if menu is footermenu1
        if( 'footermenu1' == $args->theme_location && ! $depth && $item->description )
            $item_output = str_replace( '<a ', '<a ' . $item->description .' ', $item_output );
    
        return $item_output;
      }
      add_filter( 'walker_nav_menu_start_el', 'be_header_menu_desc', 10, 4 );
    

Update:

This code seems relevant...

// via https://wordpress.stackexchange.com/a/241072/39300
  function menu_add_atts( $atts, $item, $args ) {
      $class = 'has-arrow waves-effect waves-dark nav-link'; // or something based on $item
      $atts['class'] = $class;
      return $atts;
  }
  add_filter( 'nav_menu_link_attributes', 'menu_add_atts', 10, 3 );

... however, that is imposes only the classes I specify (as opposed to any which WordPress also might). I would also like to extend it to add not just classes but also other attributes, eg. aria-expanded="false".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.