Add a Search Form to your WordPress Nav Menu

Searching in WordPress

In the recent redesign of Do It With WordPress, I wanted to include a search form in the top right corner, where the nav menu was. In order to achieve this, I decided to add a search form to the nav menu itself.

I worked with a WordPress function that allows you to edit specific menus without affecting other menus. This function is wp_nav_menu_items. And within that function, I used get_search_form to pull in the standard WordPress search form. If you want to customize the search form, see the Codex for information on how to do that.

In this example, the menu that I’m targeting is the ‘primary’ menu, as defined in my theme (look for register_nav_menus to figure out what yours is). It may be different for your own theme.

Note that get_search_form uses FALSE, which is for the echo variable, since we want to return the search form as a string.

The following snippet should go in your theme’s functions.php file (not your functionality plugin, since it is specific to the theme).

Now when you refresh your site, your menu should have a search form attached to the end of it. You can then target the CSS by using a specific ruleset (#nav-search and #nav-search #s in this case).

2 thoughts on “Add a Search Form to your WordPress Nav Menu”

  1. tammyserata says:

    Hi Dave,
    Thank you for the code to add a search box to the primary menu. I’ve tried a bunch and yours is the first and only that has worked.
    I wonder if you would mind telling me how to float the search box to the right side of the menu bar?
    Thank you again for the information you have already provided.
    Best regards,

    1. You just need to find the CSS selector for your Search Box and apply float: right; to it. You’ll also need to make sure that your menu div is wide enough to move the search box as far over as you want it.

Leave a Reply