Theme Development

Add Search Form To A WordPress Menu

Wordpress

Wordpress comes with the functionality to create menus in the dashboard area, from here you can select pages or custom custom menu items to make up your menu.

Menus are normally going to be display at the top of the page to give the visitor easy access to your main pages. But this top navigation bar is also a good place to have your search box so if people can't find what they are looking for then they can use your search box. With the default behaviour of the WordPress menus you can only add pages to the menu and not a search box.

Below is a WordPress snippet you can use to add a search form to a certain menu, just add the following to your WordPress functions.php file.

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

 function add_search_form($items, $args) {
          if( $args->theme_location == 'CHANGE-THIS-TO-YOUR-MENU-NAME' )
          $items .= '<li class="search"><form role="search" method="get" id="searchform" action="'.home_url( '/' ).'"><input type="text" value="search" name="s" id="s" /><input type="submit" id="searchsubmit" value="'. __('Search') .'" /></form></li>';
     return $items;
}
Back to top

Gain access to all tutorials

  • Premium tutorials covering WordPress, Laravel and VueJS
  • Download premium content
  • Download premium WordPress plugins
  • Only $5 a month

Join Paulund

Comments

  1. Thank for tutorial, if possible please show us How to add tab search button in menu ? on click something like that

    1. Paul says:

      Hi, you'll just need to place the search form in a hidden div. Then using the same filter you can add an element that on click event using JS display the hidden search form.