Search Form in WP Nav Menu

The WP Nav Menu is very popular and WordPress users love to implement their content in the navigation that way. Many users also like to have a search field in their navigation. In this context I found some horrible written solutions to implement the search field in the navigation. That's why I thought I write a simple yet efficient solution to have the search field in your navigation.

For this solution I'm using the default search function - get_search_form(). If you use it on another spot as well, please pay attention to the stylesheet. Otherwise the following snippet is sufficient to implement the search field in your navigation.

This function and the call belongs into functions.php of the theme and the adjustment of the stylesheet in the according file of the theme, most of the time it is style.css.

function fb_add_search_box ( $items, $args ) {
	
	// only on primary menu
	if( 'primary' === $args -> theme_location )
		$items .= '<li class="menu-item menu-item-search">' . get_search_form( FALSE ) . '</li>';
	
	return $items;
}
add_filter( 'wp_nav_menu_items', 'fb_add_search_box', 10, 2 );

If you like to implement the search form only in a specific navigation; you just need to call the entry theme_location of the argument array. If it's the menu with the string n, then ... - an example:
if( 'primary' === $args -> theme_location )

The key of the call is defined in your theme, therefore easy to find in the backend, as you can see in the screenshot above. Have fun with it!

Comments are closed.

2 comments

  1. Emiliano Jankowski

    Cool tip!!!

  2. Andy from Workshopshed

    This technique breaks if you've got a custom search form defined. See http://core.trac.wordpress.org/ticket/16541