How to add search form in the wp nav menu?

by Maruti Mohanty ·
Published November 27, 2014
· Updated December 19, 2014

WP nav menu

While finding solutions and helping others with solutions in the WordPress Support forum, I came across another small and useful piece of code. This one is about adding a WordPress search form to the WordPress navigation menu. Usually there are not many theme which is designed to have the search form in the wp nav menu and like always WordPress is flexible enough to tweak this with few lines of code.

To add a search form to the wp nav menu items, we can use the available filter “wp_nav_menu_items“. This filters allow two parameters with it ie: $items and $args. The first one is a string which lists the menu items available where as the later is an object containing the details of the corresponding nav menu.

We can add the following lines of code to the theme’s functions.php file to make this work, and like always I would suggest to make the following changes using a child theme.

PHP

1

2

3

4

5

6

7

functionse_add_search_box_to_menu($items,$args){

if($args->theme_location==='main')

return$items.get_search_form();

return$items;

}

add_filter('wp_nav_menu_items','se_add_search_box_to_menu',10,2);

The above code adds the WP search form to the wp nav menu and with some small style changes you can make the search form work with your theme. I had come across this in the support forum where the user was using a hiero theme, so by any chance if you are using the same theme then you can add the below css to the child theme’s style.css file to make it perfectly work with the theme

CSS

1

2

3

4

5

6

7

8

9

10

11

12

/* Please do adjust the position as per your need */

#main-navigation .search-form {

display:inline-flex;

position:absolute;

right:40%;

}

#main-navigation .search-field {

margin:8px020px;

}

#main-navigation .search-submit {

margin:0020px10px;

}

We can also use the wp_nav_menu_items filter to add a new wp nav menu item. This may or may not be a static item and may or may not be made available for logged in users with adding some conditions.