2016-11-22 66 views
1

有沒有一種方法可以用woocommerce產品搜索覆蓋主題的搜索查詢。我不想在網頁和文章中搜索內容,而只會在產品中搜索。用woocommerce搜索取代主題搜索功能

我搜索,發現這個:

function custom_search_query($where, &$wp_query) 
    { 
     global $wpdb; 

     if (empty($where)) 
      return $where; 

     // get search expression 
     $terms = $wp_query->query_vars[ 's' ]; 


     $where = 'wp_posts.post_type = "product"'; 

     // get searcheable_acf, a list of advanced custom fields you want to search content in 
     $list_searcheable_acf = list_searcheable_acf(); 
     foreach($exploded as $tag) : 
      $where .= " 
       AND (
       (wp_posts.post_type LIKE '%$tag%') 
       OR (wp_posts.post_content LIKE '%$tag%') 
       OR EXISTS (
        SELECT * FROM wp_postmeta 
         WHERE post_id = wp_posts.ID 
         AND ("; 
      foreach ($list_searcheable_acf as $searcheable_acf) : 
       if ($searcheable_acf == $list_searcheable_acf[0]): 
       $where .= " (meta_key LIKE '%" . $searcheable_acf . "%' AND meta_value LIKE '%$tag%') "; 
       else : 
       $where .= " OR (meta_key LIKE '%" . $searcheable_acf . "%' AND meta_value LIKE '%$tag%') "; 
       endif; 
      endforeach; 
       $where .= ") 
       ) 
       OR EXISTS (
        SELECT * FROM wp_comments 
        WHERE comment_post_ID = wp_posts.ID 
        AND comment_content LIKE '%$tag%' 
       ) 
       OR EXISTS (
        SELECT * FROM wp_terms 
        INNER JOIN wp_term_taxonomy 
        ON wp_term_taxonomy.term_id = wp_terms.term_id 
        INNER JOIN wp_term_relationships 
        ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id 
        WHERE (
        taxonomy = 'post_tag' 
         OR taxonomy = 'category'     
         OR taxonomy = 'myCustomTax' 
        ) 
        AND object_id = wp_posts.ID 
        AND wp_terms.name LIKE '%$tag%' 
       ) 
      )"; 
     endforeach; 
     return $where; 
    } 
    add_filter('posts_search', 'custom_search_query', 500, 2); 

但是,這將在搜索預先添加自定義字段。我只想搜索產品。

這可能嗎?

在此先感謝。

回答

0

您應該使用pre_get_posts過濾器來過濾搜索結果頁面中的帖子類型。例如:

add_filter('pre_get_posts', 'custom_pre_get_posts'); 
function custom_pre_get_posts($query) { 
    if (is_search()) { 
     $query->set('post_type', 'product'); 
    } 

    return $query; 
} 

這裏唯一的問題是,如果你的產品有自定義字段或屬性,它們將不會因爲WordPress默認搜索看起來只在標題和內容中包含的結果。 您提供的示例具有更復雜的搜索,並且它也查找自定義字段。但如果主要目標是除去產品以外的所有東西,那麼我的代碼就可以解決問題。

+0

感謝您的回覆。它就像一個魅力..我從過去8小時尋找解決方案..謝謝 –

0

下面的代碼應只搜索「產品」帖子類型,並將顯示在您的正常搜索存檔中。通過在name屬性中使用'post_type',您可以聲明要搜索的帖子類型。

<form action="<?php bloginfo('siteurl'); ?>" method="get" class="form-inline searchform">  
    <input type="text" name="s" value="" placeholder="Search for Products..." class="s" /> 
    <input type="hidden" name="post_type[]" value="product" /> 
    <button type="submit" class="searchsubmit">Search</button>  
</form>