How to add a search box to your WordPress menu

Unless you have removed the feature, WordPress allows your visitors to search through your entire site. We have mentioned this cool feature several times and showed you different things you could do with your search pages. For example, you could easily redirect users to the post if there’s only one result found or even set up a custom Google search.

If you have browsed through your standard WP widgets, you have probably seen that there is a search widget ready to be placed on a sidebar. But what if you want your search box to appear next to your menu instead?

In the following lines, we will show you a function which will take your everyday search box and put it in the navigation menu.

Add a search box to menu:

    1. Open functions.php
    2. Copy and paste the following:
add_filter( 'wp_nav_menu_items','add_search_box', 10, 2 );
function add_search_box( $items, $args ) {
$items .= '<li>' . get_search_form( false ) . '</li>';
return $items;
}
  1. Save changes

To be sure that the code will work for you, make sure that you have navigation menu already added to your site.

The code is pretty simple and its only function is to add the search box to your nav menu. Most probably, your search box won’t be aligned where you wanted it to be. That means you will have to tell WordPress where to put the search box:

    1. Add a class to <li> tag found on the third line of code:
$items .= '<li class=”searchbox-position”>' . get_search_form( false ) . '</li>'
    1. Save changes
    2. Open style.css
    3. Copy and paste CSS code:
.searchbox-position {
margin-top: 15px;
margin-right: 20px;
}
  1. Change the code to your liking
  2. Save changes

Hopefully, you have nested the box just perfectly next to your menu. It doesn’t take much to fit the box where you want it. Don’t forget to style the search box itself and enjoy the feature.

If you want more control over your menu and search box, check out how to add icons to your menu and how to add a voice search option for visitors who like to dictate their search terms. There is much more you can do both with your menu and your search options so test our search box and learn something new.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

3 thoughts on “How to add a search box to your WordPress menu

  1. Thank you for this post. I hace the problem that I have more than one menu, how can I choose only the primary menu in this add_filter?

  2. Sorry, I’m confused right at the beginning. You say to open “functions.php.” I have no idea what this means. I’m looking at the wordpress customization section and I see nothing related to editing php code. Perhaps I need to pay for a more expensive page paln?

Leave a Reply

Your email address will not be published. Required fields are marked *