2017-11-22 10 views
0

カテゴリ「スペアパーツ」から商品を除外して、woocommerceの商品タグのクエリ内に表示するにはどうすればよいですか?私は/ tags /内のすべての製品をリストしたいが、その製品がカテゴリ "スペアパーツ"の内部にある場合は、そこにフォントリストを入れるだけです。私はそのためにどの機能を使う必要があるのですか?商品タグ内の特定の商品カテゴリからWoocommerce商品を除外する

私はそれをウェブで検索しましたが、それはうまく動作します。

+0

あなたはこの問題を解決するために試してみましたか? MySQLを使用する予定がある場合、これらのテーブルはどのように構造化されていますか? https://stackoverflow.com/help/how-to-ask –

答えて

1

woocommerce_product_query_tax_queryフィルタフックにフックされたこのカスタム関数では、これを簡単に行うことができます。

ので"spare-parts"製品カテゴリスラッグからのすべての製品は、製品タグのアーカイブページから除外されます。

ここではそのコードです:

add_filter('woocommerce_product_query_tax_query', 'exclude_specific_product_category_query', 10, 2); 
function exclude_specific_product_category_query($tax_query, $query) { 
    // Only on Product Tag archives pages 
    if(is_admin() || ! is_product_tag()) return $tax_query; 

    // HERE Define your product category SLUGs to be excluded 
    $terms = array('spare-parts'); // SLUGs only 

    // The taxonomy for Product Categories 
    $taxonomy = 'product_cat'; 

    // Add your criteria 
    $tax_query[] = array(
     'taxonomy' => $taxonomy, 
     'field' => 'slug', // Or 'name' or 'term_id' 
     'terms' => $terms, 
     'operator' => 'NOT IN', // Excluded 
    ); 

    return $tax_query; 
} 

コードは、あなたのアクティブな子テーマ(またはテーマ)のfunction.phpファイルやも任意のプラグインファイルになります。

テスト済みで動作します。


ですから、これはあなたには、いくつかの製品カテゴリを除外すると、いくつかの製品のタグが含まれますどこが似てtax_queryを使用しますWP_queryで使用する必要がある場合...

それがする。この例では、製品IDの昏睡区切り文字列を出力します。

// HERE Define your product category SLUGs to be excluded 
$terms_cat = array('spare-parts'); // SLUGs only 

// HERE Define your product tag SLUGs to be included 
$terms_tag = array('special', 'wear'); // SLUGs only 

// The taxonomies 
$taxonomy_tag = 'product_tag'; // Product tag 
$taxonomy_cat = 'product_cat'; // Product Category 

// The Query 
$loop = new WP_Query(array(
    'post_type' => 'product', 
    'post_status' => 'publish', 
    'posts_per_page' => -1, 
    'order' => 'ASC', 
    'tax_query' => array(
     'relation' => 'AND', 
     array(// The tag query (Include) 
      'taxonomy' => $taxonomy_tag, 
      'field' => 'slug', 
      'terms' => $terms_tag, 
     ), 
     array(// the category query (exclude) 
      'taxonomy' => $taxonomy_cat, 
      'field' => 'slug', // Or 'name' or 'term_id' 
      'terms' => $terms_cat, 
      'operator' => 'NOT IN', // Excluded 
     ), 
    ) 
)); 

if ($loop->have_posts()): 
    while ($loop->have_posts()): 
     $loop->the_post(); 
     $products_ids[] = $loop->post->ID; // Set the product Ids in an array 
    endwhile; 
endif; 

// always reset the WP_Query 
wp_reset_query(); 

// Convert the array in a string with all product Ids coma separated 
$product_ids_string = implode(', ', $products_ids); 

// Output Ids 
echo $product_ids_string; 

テスト済みで動作します。


関連資料:WP_Query - Taxonomy Parameters

+1

クイックアンサーで感謝します。「endif;」というエラーが表示されます。コードライン –

+0

@ DigitalWhirlLLC私は大きなアップデートをしました(私はこの答えを終えていました)。そしてこの小さな間違いを修正しました。あなたは今あなたのものを作るためにすべてを持っています – LoicTheAztec

関連する問題