Customizing Only a Specific Menu using the “wp_nav_menu_items” Hook?

Thanks to some help on here, I’ve managed to add a custom search box to my main menu… by adding this to my theme’s functions.php

add_filter('wp_nav_menu_items','search_box_function');
  function search_box_function ($nav){
  return $nav."<li class='menu-header-search'><form action='http://example.com/' id='searchform' method='get'><input type='text' name='s' id='s' placeholder='Search'></form></li>";
}

However, I’ve now added another menu to put in the footer, but the search box gets added to this one too. How would I add the search box to the primary menu only?

My code for registering the menus is:

register_nav_menus( array(
  'primary' => __( 'Primary Navigation', 'twentyten' ),
  'secondary'=>__('Secondary Menu', 'twentyten' ),

 ) );

..and the code to display the secondary menu is:

wp_nav_menu( array( 'container_class' => 'menu-header', 'theme_location' => 'secondary' ) );

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

To only add the custom search box to the main menu you could pass the second parameter provided by the wp_nav_menu_items filter and check if the theme_location is the primary location

add_filter('wp_nav_menu_items','search_box_function', 10, 2);
function search_box_function( $nav, $args ) {
    if( $args->theme_location == 'primary' )
        return $nav."<li class='menu-header-search'><form action='http://example.com/' id='searchform' method='get'><input type='text' name='s' id='s' placeholder='Search'></form></li>";

    return $nav;
}

Method 2

An alternative method of doing this is adding the menu slug to the wp_nav_menu_items filter.

For example, let’s say you have a menu named Header and you always want this menu (whether it’s attached to a theme location or not) to display a search box. You can do so by adding the menu slug, in this case header, to the filter.

The new filter would be as follows:

add_filter( 'wp_nav_menu_header_items', 'search_box_function' );

Notice the header portion of the new filter. This tell WordPress what menu to add the function to.

This is just one different way to approach your current problem.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x