如果一个变体在 WooCommerce 中缺货,则将所有变体设置为缺货

Set all variations out of stock if one variation is out of stock in WooCommerce

我们 运行 一个带有 WooCommerce 的自助存储系统,我们使用 WooCommerce 订阅插件。我们的存储单元是具有可变订阅的独特产品。每个变体都有不同的计费周期(1 个月、3 个月、6 个月和 12 个月)。如果一个变体缺货,我需要整个父产品或至少所有变体都缺货。

我没有找到任何相关设置,也没有找到实现方法。

感谢任何帮助。

当一个变体缺货时,以下将使所有变体缺货(对于特定可变产品)(也适用于 WooCommerce 订阅):

add_filter('woocommerce_available_variation', 'set_all_variations_out_of_stock', 10, 3 );
function set_all_variations_out_of_stock( $data, $product, $variation ) {
    // Set the Id(s) of the related variable product(s) below in the array
    if( in_array( $product->get_id(), array(738) ) ){
        $out_of_stock = false; // initializing
        
        // Loop through children variations of the parent variable product
        foreach( $product->get_visible_children() as $_variation_id ) {
            if( $_variation_id != $data['variation_id'] ) {
                $_variation = wc_get_product($_variation_id);
                
                
                if( ! $_variation->is_in_stock() ) {
                    $out_of_stock = true; // Flag as out of stock
                    break;
                }
            }
        }
        if ( $out_of_stock ) {
            $data['availability_html'] = '<p class="stock out-of-stock">'. __('Out of stock', 'woocommerce') .'</p>';
            $data['is_in_stock'] = false;
        }
    }
    return $data;
}

代码进入您的活动子主题(活动主题)的 function.php 文件。已测试并有效。


Important note:

Stock can be managed on the parent variable product.

  1. Enable stock management on the variable product (on Inventory tab) and set the stock there.
  2. Disable stock management on each variation for this variable product.

You are done. The stock management is now handled on the variable product.