将搜索栏添加到 wordpress 中的导航菜单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31822842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
adding search bar to the nav menu in wordpress
提问by Elroy Fernandes
http://www.lundarienpress.com/( this is a wordpress site)
http://www.lundarienpress.com/(这是一个 wordpress 网站)
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.
我还没有找到办法做到这一点。我希望论坛上的某个人可以帮助我。
回答by heytricia
@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.
@rockmandew 是对的 - 如果不将 get_search_form() 设置为 false,此代码不应该工作。但即使进行了更改,该功能也不起作用。
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'.
值得注意的是,我的主导航在我的函数文件中被命名为“primary”。这可能因主题而异,因此需要相应地更改,即“main”或初始解决方案中的“header_menu”。
回答by Dr.Tricker
Function.php code:
函数.php代码:
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.
这get_search_form()
是获取搜索框的功能。