How to Add a Search Bar to the WordPress Menu

Home » Snippets » How to Add a Search Bar to the WordPress Menu
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

If you’re looking to make your WordPress site more user-friendly, adding a search box to your menu bar can be a great way to help visitors quickly find what they’re looking for. In this article, we’ll show you how to easily add a search box to your WordPress menu. With just a few simple steps, you can improve the navigability of your site and enhance your visitor’s experience. Let’s dive in!

					function wpturbo_add_search_to_menu( $items, $args ) {
    if ( $args->theme_location == 'primary' ) {
        $items .= '<li class="menu-item menu-item-search"><form method="get" action="' . home_url() . '"><input type="text" placeholder="Search" name="s" /><button type="submit">&#128269;</button></form></li>';
    }
    return $items;
}
add_filter( 'wp_nav_menu_items', 'wpturbo_add_search_to_menu', 10, 2 );
				

In this tutorial, we will be discussing how to add a search bar to your WordPress menu using code. This can be a useful feature for your site users to easily search for content.

The code snippet defines a new function called wpturbo_add_search_to_menu(). The function takes two parameters – $items and $args.

The $items parameter contains the HTML markup for the menu items, and $args contains arguments for the current menu.

We use a conditional statement to check if the current location of the menu is the primary menu. If it is, then we add the HTML markup for the search bar as a new menu item.

if ( $args->theme_location == 'primary' ) {
    $items .= '<li class="menu-item menu-item-search"><form method="get" action="' . home_url() . '"><input type="text" placeholder="Search" name="s" /><button type="submit">&#128269;</button></form></li>';
}

In this code snippet, we create a new list item (<li>) and assign it the class of menu-item and menu-item-search. We then embed a form element within the list item, which contains an input field with the name of s for the search term and a submit button with an icon. We set the action attribute of the form to be the home URL of our WordPress site.

Finally, we use the return statement to return the modified menu items to the wp_nav_menu_items filter.

return $items;

By hooking into this filter, our custom function wpturbo_add_search_to_menu will be executed whenever WordPress outputs the menu items for the primary menu location.

Register an account to save your snippets or go Pro to get more features.