今天的程式碼片段實際上來自我自己的網站。您可能已經注意到,導航選單中有一個 “放大鏡” 可以向下滾動到搜尋欄。我專門搜尋部落格文章(我排除頁面,產品等)。這是我如何做到的 – 希望您今天能夠學到新的東西!

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 &hellip;','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 中文論壇提問,會有專業技術團隊提供相關幫助。