
Do you ever wanted to be able to automatically add a search field to WP 3.0+ navigation menus? If yes, just have a look to today’s recipe, you’ll probably love it!

Do you ever wanted to be able to automatically add a search field to WP 3.0+ navigation menus? If yes, just have a look to today’s recipe, you’ll probably love it!
Open your functions.php file, and paste the following code. The search field will be displayed once you saved the file.
add_filter('wp_nav_menu_items','add_search_box', 10, 2);
function add_search_box($items, $args) {
ob_start();
get_search_form();
$searchform = ob_get_contents();
ob_end_clean();
$items .= '<li>' . $searchform . '</li>';
return $items;
}
Thanks to Ronald for the cool tip!
8 Responses
This didn’t work for me. Does it matter what theme you’re using? What does “wp_nav_menu_items” referring to?
Didn’t work for me either.
Make sure you guys go to the right theme (the theme you selected) and add it there. *** make sure you save.
Hi William, I am using magazine basic theme, which also uses wp_nav function to introduce menu, problem with me, is that i have customized search form for example code is under given how can i add this to my site’s nav bar, or is there any option how i can exempt of nav bar, so i will place it manually after adding my form code?
thank you.
This works as charm. But one issue i have…
My website has 2 menu bars and i want to add the search box to only one of them..the main navigation one. Hope you can help..thanks in advance
Pile of shite. Returns an error ‘Call to undefined function add_filter() in…’
Worked great! For those that it didn’t work for, it depends how your nav menu is called, as another similar code didn’t work for me.
Somehow my text got messed up in the last comment. Try this:
If you have multiple menus and want to add the search bar to just one menu add
if( $args->theme_location == ‘main_navi’ )
above the line $items .= ” . $searchform . ”;
in the code at the beginning of this article:
Depending on your theme you may have a different name for main_navi. It could be called navi or top_navi or another name.
Search your functions.php file for register_nav_menu to find the names of your menus. You need to use one of those names.
Also check Menus under Appearance in your WordPress dashboard to see which menu you selected as your main menu.
Trackbacks: