![](/img/trans.png)
[英]Display a Sold out greyed button if all variations are out of stock in WooCommerce
[英]How do I show sold/out of stock items in a certain Woocommerce category archive page, but not display them in others?
我想在一個類別存檔頁面上顯示“缺貨”商品:“已售商品”。
所有其他類別都需要隱藏其缺貨商品。
'隱藏目錄中缺貨的物品',在 WC 設置中沒有打勾。
我有下面的代碼,它成功地隱藏了缺貨商品,但我無法讓 has_term() 函數正常工作並過濾掉“已售商品”頁面。
我相信這可能是因為我正在使用 'pre_get_posts' 並且這可能是在添加 'Sold Items' 術語之前觸發的。
哪個是最好的鈎子動作? 或者我需要把它分成兩個鈎子嗎?
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 );
}
}
}
最好使用高級 WooCommerce 特定過濾器掛鈎,而不是低級 WordPress 掛鈎,因為后者可能會導致頭痛和麻煩。 (例如pre_get_posts
)對於您的場景,我建議使用woocommerce_product_query_tax_query
過濾器鈎子。 假設您有一個包含所有缺貨產品的類別,以及 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:函數名在 PHP 中不區分大小寫 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.