问题
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.
回答1:
Function.php code:
function add_last_nav_item($items, $args) {
if ($args->menu == 'header_menu') {
$homelink = get_search_form();
$items = $items;
$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.
回答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'.
来源:https://stackoverflow.com/questions/31822842/adding-search-bar-to-the-nav-menu-in-wordpress