今天的代码片段实际上来自我自己的网站。您可能已经注意到,导航菜单中有一个 “放大镜” 可以向下滚动到搜索栏。我专门搜索博客文章(我排除页面,产品等)。这是我如何做到的 – 希望您今天能够学到新的东西!

PHP 代码段:将自定义搜索栏添加到您的 WooCommerce 页眉/页脚
/**
* @snippet WooCommerce Custom Search Bar
* @sourcecode https://businessbloomer.com/?p=21175
* @author Rodolfo Melogli
* @testedwith WooCommerce 2.6.4
*/
// ----------------------------------
// 1. ADD SEARCH TO STOREFRONT FOOTER
add_action('storefront_footer','add_search_to_footer');
function add_search_to_footer() {
get_search_form();
}
// ----------------------------------
// 2. LIMIT SEARCH TO POSTS OR PRODUCTS ONLY
function SearchFilter($query) {
if ( !is_admin() && $query->is_search ) {
$query->set('post_type', 'post'); // OR USE 'PRODUCT'
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
// ----------------------------------
// 3. CHANGE PLACEHOLDER & BUTTON TEXT
function storefront_search_form_modify( $html ) {
return str_replace( array('Search …','Search'), array('WooCommerce Hooks, Storefront Theme, Google AdWords...','Search Article'), $html );
}
add_filter( 'get_search_form', 'storefront_search_form_modify' );
// ------------------------------
// 4. ADD SEARCH ICON TO NAVIGATION MENU
function new_nav_menu_items($items) {
$searchicon = '<li class="search"><a href="#colophon"><i class="fa fa-search" aria-hidden="true"></i></a></li>';
$items = $items . $searchicon;
return $items;
}
add_filter( 'wp_nav_menu_additional-resources_items', 'new_nav_menu_items' );
那就是🙂现在给我的搜索框去看看它是否有效!
可以在哪里添加此代码?
您可以将 PHP 代码片段放置在主题或子主题的 functions.php 文件的底部(如果是 CSS 代码,请添加到主题的 style.css 文件底部),修改之前建议先备份原始文件,若出现错误请先删除此代码。
这段代码是否正常可用?
或者是您有更好的解决方案想要分享?请到薇晓朵 WooCommerce 中文论坛留言告知,我们希望可以帮到更多国内的 WooCommerce 用户也希望您的参与。
需要关于 WooCommerce 的帮助?
请观看我们提供的免费视频教程或到薇晓朵 WooCommerce 中文论坛提问,会有专业技术团队提供相关帮助。