购物车中缺货时隐藏运输方式

时间:2019-10-10 18:08:11

标签: wordpress woocommerce inventory shipping-method

当购物车中的产品库存为0或更少时,我试图隐藏除其中一种以外的所有运输方式。我尝试过但无法使用的代码如下:

add_filter( 'woocommerce_available_shipping_methods', 'hide_shipping_based_on_quantity' ,    10, 1 );
function check_cart_for_oos() {
    // load the contents of the cart into an array.
    global $woocommerce;
    $found = false;
    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
        $_product = $values['data'];
        $_product_quantity = $_product->get_stock_quantity();
        $_cart_quantity = $values['quantity'];
        if (($_product_quantity <= 0) || ($_cart_quantity > $_product_quantity)) {
            $found = true;
            break;
        }
    }
    return $found;
}


function hide_shipping_based_on_quantity( $rates ) {
     $targeted_method_id = 'flat_rate:2';
     // use the function check_cart_for_oos() to check the cart for products with 0 stock.
     if( check_cart_for_oos()) {
        foreach ( $rates as $rate_key => $rate ) {
            if ( $rate->id != $targeted_method_id ) {
                unset($rates[$rate_key]);
            }
        }
    }
// return the available methods without the one you unset.
return $rates;
}

这个想法是,当有1种产品的库存为0或更少时,仅适用经济运输方式。

0 个答案:

没有答案