Post Pic

How to automatically add a search field to your navigation menu

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

Jun 24 2012 23:10

This didn’t work for me. Does it matter what theme you’re using? What does “wp_nav_menu_items” referring to?

Jul 16 2012 22:02

Didn’t work for me either.

Aug 20 2012 22:34

Make sure you guys go to the right theme (the theme you selected) and add it there. *** make sure you save.

Sep 17 2012 17:11

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.

Sep 19 2012 22:58

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

Nov 09 2012 02:49

Pile of shite. Returns an error ‘Call to undefined function add_filter() in…’

Feb 04 2013 02:18

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.

May 17 2013 00:12

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:

Leave a Comment

* Name, Email, Comment are Required

WP Theme of the week

Sponsored Likebox