您可以创建自定义条件函数来检查变量产品的所有变体是否“缺货”,如下所示:
function is_variable_product_out_of_stock( $product ) {
$children_count = 0; // initializing
$variation_ids = $product->get_visible_children();
// Loop through children variations of the parent variable product
foreach( $variation_ids as $variation_id ) {{
$variation = wc_get_product($_variation_id); // Get the product variation Object
if( ! $variation->is_in_stock() ) {
$children_count++; // count out of stock children
}
}
// Compare counts and return a boolean
return count($variation_ids) == $children_count ? true : false;
}
然后,您将在下面重新访问的挂钩函数中使用它:
add_action( 'woocommerce_before_shop_loop_item_title', 'display_products_loop_out_of_stock' );
function display_products_loop_out_of_stock() {
global $product;
if ( ( ! $product->is_type('variable') && ! $product->is_in_stock() )
|| ( $product->is_type('variable') && is_variable_product_out_of_stock( $product ) ) ) {
echo '<span class="soldout">Sold Out</span>';
}
}
代码位于活动子主题(或活动主题)的 functions.php 文件中。它应该有效。