adding search bar to the nav menu in wordpress

27,573

Solution 1

Function.php code:

function add_last_nav_item($items, $args) {
  if ('header_menu' === $args->menu_id) {
        $homelink = get_search_form(false);
        $items .= '<li>'.$homelink.'</li>';
        return $items;
  }
  return $items;
}
add_filter( 'wp_nav_menu_items', 'add_last_nav_item', 10, 2 );

Here get_search_form() is function to get search box.

Solution 2

@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'.

Share:
27,573
Elroy Fernandes
Author by

Elroy Fernandes

I am a aspiring web developer who is growing every day. I would like to share what I know with other people.

Updated on July 09, 2022

Comments

  • Elroy Fernandes
    Elroy Fernandes almost 2 years

    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.