WordPress Nav Menu Search Form without any plugin.

menu-search-form-without-any-plugin

Having a WordPress nav menu search form on your website creates a good impression on your users. It makes searching for any content on your website make easy. It is easy to have this feature in some of the paid themes and also using the plugins. but using the extra plugin in your WordPress website makes it adds an extra set of js and CSS files which makes the response time longer and it affects your page speed. I got in the situation with the free theme, where I am having the search form in the desktop and tablet view in the website menu but not in the Mobile view of the website. So, I have done some research and found this solution and like to share this with everyone to help the dev community for good.

Example:

/**
 * Add search box to mobile menu
 */
function chs_nav_search($items, $args) {
    // If this isn't the primary menu, do nothing
    if($args->theme_location == 'mobile')
    {
    	return $items . '<li id="mobile-search-chs-form">' . get_search_form(false) . '</li>';
    }
    else
    {
    	return $items;
    }
    // add search form
}
add_filter('wp_nav_menu_items', 'chs_nav_search', 10, 2);

You can see here in this post, I have returned the modified $items argument for the mobile menu location. You can change that location to whatever other mobile location you want. Like primary or other menu locations you have on your website.

By using the get_search_form() to get the WordPress default search form and the wp_nav_menu_items filter for the menu item adjustments to your desired menu items, you have your nav menu search form working. This will also help you to do enhancements in your menu display modifications if you want.

You can check the detail about the get_search_form() function here.
To get to know more about other JQuery topics, you can check these articles too.

Please follow and like us:

Related Posts

Leave a Reply

Share