PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 8, 2022

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

 November 08, 2022     menu, wordpress, wp-nav-menu-item     No comments   

Issue

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



Answered By - Sajjad Hossain Sagor
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing