[英]How do I show sold/out of stock items in a certain Woocommerce category archive page, but not display them in others?
I want to display 'Out of Stock' items on one category archive page: 'Sold Items'.我想在一个类别存档页面上显示“缺货”商品:“已售商品”。
All other categories need to hide its Out of Stock items.所有其他类别都需要隐藏其缺货商品。
'Hide out of stock items from the catalog', within the WC settings is not ticked. '隐藏目录中缺货的物品',在 WC 设置中没有打勾。
I have the below code, which successfully hides out of stock items, but I cannot get the has_term() function to work correctly and filter out the 'Sold Items' page.我有下面的代码,它成功地隐藏了缺货商品,但我无法让 has_term() 函数正常工作并过滤掉“已售商品”页面。
I believe it may be because I'm hooking into 'pre_get_posts' and perhaps this fires before the 'Sold Items' term has been added.我相信这可能是因为我正在使用 'pre_get_posts' 并且这可能是在添加 'Sold Items' 术语之前触发的。
Which is the best action to hook into?哪个是最好的钩子动作? Or do I need to split this over two hooks?或者我需要把它分成两个钩子吗?
add_action( 'pre_get_posts', 'VG_hide_out_of_stock_products' );
function VG_hide_out_of_stock_products( $q ) {
if ( ! $q->is_main_query() || is_admin() ) {
return;
}
global $post;
if ( !has_term( 'Sold Items', 'product_cat', $post->ID ) ) {
if ( $outofstock_term = get_term_by( 'name', 'outofstock', 'product_visibility' ) ) {
$tax_query = (array) $q->get('tax_query');
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'term_taxonomy_id',
'terms' => array( $outofstock_term->term_taxonomy_id ),
'operator' => 'NOT IN'
);
$q->set( 'tax_query', $tax_query );
}
}
}
It's better to use a high level WooCommerce specific filter hook, instead of low level WordPress hooks which could cause headache and trouble.最好使用高级 WooCommerce 特定过滤器挂钩,而不是低级 WordPress 挂钩,因为后者可能会导致头痛和麻烦。 (eg pre_get_posts
) For your scenario I suggest woocommerce_product_query_tax_query
filter hook. (例如pre_get_posts
)对于您的场景,我建议使用woocommerce_product_query_tax_query
过滤器钩子。 Assuming you have a category with all out of stock products in it, with slug sold-items
, the final code could be something like this:假设您有一个包含所有缺货产品的类别,以及 slug sold-items
,最终代码可能是这样的:
add_filter( 'woocommerce_product_query_tax_query', 'vg_hide_out_of_stock_products' );
function vg_hide_out_of_stock_products( $tax_query ) {
if( !is_shop() && !is_product_category() && !is_product_tag() ) {
return $tax_query;
}
if( is_product_category('sold-items') ) {
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'slug',
'terms' => ['outofstock'],
'operator' => 'IN',
);
} else {
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'slug',
'terms' => ['outofstock'],
'operator' => 'NOT IN',
);
}
return $tax_query;
}
PS: Function names are not case sensitive in PHP :) PS:函数名在 PHP 中不区分大小写 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.