adding search bar to the nav menu in wordpress

Elroy Fernandes picture Elroy Fernandes · Aug 5, 2015 · Viewed 26k times · Source

http://www.lundarienpress.com/ ( this is a wordpress site)

This is my site, I am trying to add a search bar to the nav menu and have it to the right. Any ideas ?

I have not found a way to do it. I am hoping some one from the forum can help me.

Answer

heytricia picture heytricia · Jan 9, 2017

@rockmandew is right - this code shouldn't work without setting get_search_form() to false. But even after making that change, the function wouldn't work.

I initially added a search form to my nav menu by adding this to my functions file:

/**
 * Add search box to nav menu
 */
function wpgood_nav_search( $items, $args ) {
    $items .= '<li>' . get_search_form( false ) . '</li>';
    return $items;
}
add_filter( 'wp_nav_menu_items','wpgood_nav_search', 10, 2 );

This is a good solution if you have one menu or want a search box added to all menus. In my case, I only wanted to add a search box to my main menu. To make this happen, I went with this:

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

It's worth noting my main nav is named 'primary' in my functions file. This can vary by theme, so this would need to be changed accordingly, i.e. 'main' or as in the initial solution, 'header_menu'.