wordpressmenuwp-nav-menu-item

How can I dynamically add a new menu item to the beginning of a specific WordPress menu?


I have 4 menus registered within my WordPress theme.

register_nav_menus( array(
    'menu-1' => esc_html__( 'Primary', 'honeycomb' ),
    'menu-2' => esc_html__( 'Mobile Cat Products', 'honeycomb' ),
    'menu-3' => esc_html__( 'Top Bar', 'honeycomb' ),
    'menu-4' => esc_html__( 'Shopify Nav', 'honeycomb' ),
) );

I need to dynamically insert a new menu link at the beginning of menu-4 From what I understand its possible to filter a specific menu using a variant of wp_nav_menu_items by simply passing in the theme location name of the menu. In my case 'menu-4'.

add_filter( 'wp_nav_menu_menu-4_items', 'prefix_add_menu_item', 10, 2 );

function prefix_add_menu_item ( $items, $args ) {
   $items .=  '<li class="menu-item">My New Item Here</li>';

   return $items;
}

However this is not working. I am not sure what I am missing here.


Solution

  • The $menu->slug here apply_filters( "wp_nav_menu_{$menu->slug}_items", $items, $args ); is not the nav menu id... it's the Menu Name slug... like here i have named my Menu as Main Menu so the slug becomes main-menu so your filter would be...

    add_filter( 'wp_nav_menu_main-menu_items', 'so68759013_add_menu_item', 10, 2 );
    
    function so68759013_add_menu_item( $items, $args )
    {   
      $items .=  '<li class="menu-item">My New Item Here</li>';
    
      return $items;
    }
    

    Menu