How to add class to parent a tag with a sub menu

I have been trying to add a class to the parent a tag of a sub menu using a custom walker. The current walker I am using adds the class to the parent <li>, does anybody know how to adjust this to add the class to the parent <a> tag instead.

Here is the existing walker I am using:

Read More
class My_Walker_Nav_Menu extends Walker_Nav_Menu{
  public function display_element($el, &$children, $max_depth, $depth = 0, $args, &$output){
    $id = $this->db_fields['id'];    

    if(isset($children[$el->$id]))
      $el->classes[] = 'toggle-sub-nav closed';    

    parent::display_element($el, $children, $max_depth, $depth, $args, $output);
  }
}

Here is the code that is output:

screen shot of current code output

Here is the code that I am aiming for:

Screen shot of desired code output with class applied to the a tag

Related posts

1 comment

  1. You can simply add this code snippet in your theme’s functions.php file.

    /* Add classes and other attributes to the anchor tags if list item is a parent */
    
    add_filter( 'nav_menu_link_attributes', 'add_class_to_items_link', 10, 3 );
    
    function add_class_to_items_link( $atts, $item, $args ) {
      // check if the item has children
      $hasChildren = (in_array('menu-item-has-children', $item->classes));
      if ($hasChildren) {
        // add the desired attributes:
        $atts['class'] = 'your-custom-class'; //This is the main concern according to the question
        $atts['id'] = 'your-custom-id'; //Optional
        $atts['data-toggle'] = 'dropdown'; //Optional
        $atts['data-target'] = '#'; //Optional
      }
      return $atts;
    }
    

Comments are closed.