Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding search bar to the nav menu in wordpress

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.

like image 308
Elroy Fernandes Avatar asked Dec 03 '22 16:12

Elroy Fernandes


2 Answers

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

like image 97
heytricia Avatar answered Dec 22 '22 12:12

heytricia


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.

like image 40
Dr.Tricker Avatar answered Dec 22 '22 13:12

Dr.Tricker