[英]Exclude Woocommerce products from a specific product category inside product tags
如何将产品从“备件”类别中排除,以显示在woocommerce产品标签查询中? 我想在/ tags /中列出所有产品,但是如果该产品在“备件”类别中,则只需在其中列出字体即可。 我需要使用哪个功能。
我在网上搜索了该信息,但它确实起作用。
在挂接到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文件中,或者在任何插件文件中。
经过测试和工作。
因此,如果需要在WP_query
使用WP_query
,则将使用类似的tax_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-分类参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.