php 如何根据WooCommerce中的不同条件更改单个产品页面上的“库存管理”可用性文本

bxgwgixi  于 2022-11-28  发布在  PHP
关注(0)|答案(1)|浏览(143)

我正试图根据WooCommerce中的不同条件更改单个产品页面上的stock management可用性文本。
根据“启用产品级库存管理”是on还是off,有5种情况。
1.开启,数量:0
1.开启,数量:2
1.开启,数量:3个以上
1.已关闭,缺货
1.已关闭,有库存
我在用

add_filter( 'woocommerce_get_availability', 'wcs_custom_get_availability', 1, 2);
function wcs_custom_get_availability( $availability, $_product ) {
   global $product;

    // Case 3
    if ( $_product->is_in_stock() ) {
        $availability['availability'] = __('3. Turned on, Quantity: 3+', 'woocommerce');
    }

    // Case 2
    if ( $_product->is_in_stock() && $product->get_stock_quantity() <= 2 ) {
        $availability['availability'] = sprintf( __('2. Turned on, Quantity: 2', 'woocommerce');
    }

   // Case 5
    if ( $_product->is_in_stock() && $product->get_stock_quantity() <= 0 ) {
        $availability['availability'] = sprintf( __('5. Turned off, In stock', 'woocommerce'));
    }
    
    // Case 4 and 1 - out of stock
    if ( ! $_product->is_in_stock() ) {
        $availability['availability'] = __('4. Turned off, Out of stock / 1. Turned on, Quantity: 0', 'woocommerce');
    }

    return $availability;
}

但如何让它为可变产品工作呢?
对于简单产品,它工作完美,但对于可变产品,2种(共5种)情况显示错误结果:
1.开启,数量:0 [工作正常]
1.开启,数量:2 [错误-显示案例编号5]
1.开启,数量:3+ [错误-显示病例编号5]
1.已关闭,缺货[工作正常]
1.已关闭,有库存[工作正常]

htrmnn0y

htrmnn0y1#

if $product->get_stock_quantity() <= 0 than $_product->is_in_stock()将始终为false,因为库存编号小于0或等于0,因此您的逻辑中存在错误。
也没有必要混合使用global $product$_product,因为$_product已经包含了产品对象。

  • $product->managing_stock()可能会派上用场

因此,您可以改用:

// Change In Stock Text
function filter_woocommerce_get_availability( $availability, $product ) {       
    // Managing stock is activated
    if ( $product->managing_stock() ) {
        // Stock quantity
        $stock_quantity = $product->get_stock_quantity();
        
        // Compare
        if ( $stock_quantity <= 0 ) {
            $availability['availability'] = __('1. Turned on, Quantity: less then or equal to 0', 'woocommerce' );
        } elseif ( $stock_quantity > 0 && $stock_quantity <= 2 ) {
            $availability['availability'] = __('2. Turned on, Quantity: 1 or 2', 'woocommerce' );           
        } elseif ( $stock_quantity > 3 )  {
            $availability['availability'] = __('3. Turned on, Quantity: 3+', 'woocommerce' );
        }
    } else {
        // In stock
        if ( $product->is_in_stock() ) {
            $availability['availability'] = __('4. Turned off, In stock', 'woocommerce' );      
        } else {
            $availability['availability'] = __('5. Turned off, Out of stock', 'woocommerce' );              
        }
    }

    return $availability;
}
add_filter( 'woocommerce_get_availability', 'filter_woocommerce_get_availability', 10, 2 );

相关问题