Php 当所有变体缺货时,显示WooCommerce可变产品的售罄情况

Php 当所有变体缺货时,显示WooCommerce可变产品的售罄情况,php,wordpress,woocommerce,stock,product-variations,Php,Wordpress,Woocommerce,Stock,Product Variations,在WooCommerce中,我使用以下功能,如果产品缺货,它会在产品缩略图上添加售罄文本: add_action( 'woocommerce_before_shop_loop_item_title', 'bbloomer_display_sold_out_loop_woocommerce' ); function bbloomer_display_sold_out_loop_woocommerce() { global $product; if ( ! $product-&g

在WooCommerce中,我使用以下功能,如果产品缺货,它会在产品缩略图上添加售罄文本:

add_action( 'woocommerce_before_shop_loop_item_title', 'bbloomer_display_sold_out_loop_woocommerce' );
 
function bbloomer_display_sold_out_loop_woocommerce() {
    global $product;
    if ( ! $product->is_in_stock() ) {
        echo '<span class="soldout">Sold Out</span>';
    }
} 
add_action('woocommerce_-before_-shop_-loop_-item_-title'、'bbloomer_-display_-sall_-out_-loop_-woocommerce');
功能bbloomer\u display\u Sald\u out\u loop\u woocommerce(){
全球$产品;
如果(!$product->库存中(){
echo“售罄”;
}
} 
它适用于简单产品,但不适用于可变产品

对于有变化的可变产品,如果我将除1个变化外的所有变化都设置为0库存量,我注意到缩略图上仍然显示售罄消息。从技术上讲,这是不正确的,因为我们确实有一些库存


有人知道如何更改下面的代码来处理此问题吗?

您可以创建一个自定义条件函数来检查变量产品的所有变体是否“缺货”,如下所示:

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>';
    }
} 
add_action('woocommerce_-before_-shop_-loop_-item_-title','display_-products_-loop_-out_-stock');
功能显示\u产品\u循环\u输出\u库存(){
全球$产品;
如果(!$product->is_type('variable')&&&!$product->is_in_stock())
||($product->is_类型('variable')&&is_variable_产品库存不足($product))){
echo“售罄”;
}
} 
代码进入活动子主题(或活动主题)的functions.php文件。它应该有效