Many times you need to add a search form to a WordPress menu bar. Most of the modern/premium themes already have a search option to be added at the menu bar, top bar. You can enable or disable this option from your themes options panel. But there are many free themes that don’t provide this option. In that case, we need to add the plugin or customize the theme to achieve the goal.
In this post, I will show you how to add a search form to a WordPress menu.
Add the following code snippet to your theme functions.php
add_filter('wp_nav_menu_items', 'add_search_form_to_menu', 10, 2);
function add_search_form_to_menu($items, $args) {
if( $args->theme_location == '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;
}
Don’t forget to change the menu name in the above code snippet.
You can also add a search form to a WordPress menu by using Add Search to Menu Plugin.
If you need any help, don’t hesitate to contact us.