2016-11-22 21 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> 
関連する問題