Search code examples
wordpressmenunavigation

Wordpress add link if item has submenu


I want to add a button for a responsive dropdown in a wordpress menu, which I can trigger with javascript. For that I need a custom link with an icon or something like that after the a-tag but inside the li-tag. How can I check a menuitem if it has a submenu and add a custom a-tag inside?

I've tried the walker and add_filter function, but it doesn't work.

Can anybody help me?

Thanks


Solution

  • If you add this to your function.php file, it will add class dropdown to all the parent menus with children (submenus). Then you can target .dropdown with javascript.

    function menu_set_dropdown( $sorted_menu_items, $args ) {
      $last_top = 0;
      foreach ( $sorted_menu_items as $key => $obj ) {
          // it is a top lv item?
          if ( 0 == $obj->menu_item_parent ) {
              // set the key of the parent
              $last_top = $key;
          } else {
              $sorted_menu_items[$last_top]->classes['dropdown'] = 'dropdown';
          }
      }
      return $sorted_menu_items;
    }
    add_filter( 'wp_nav_menu_objects', 'menu_set_dropdown', 10, 2 );