Скрыть способы доставки, когда товар на складе находится в корзине - PullRequest
0 голосов
/ 10 октября 2019

Я пытаюсь скрыть все способы доставки, кроме одного, когда в корзине есть товар с 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 или меньше запасом, применяется только экономичный способ доставки.

...