Pregunta

I've used a table rate shipping plugin to set up 4 shipping zones with each zone having a Standard and Next Day delivery option.

Every item in the store is available within 10-15 days but a number of products are in stock and available for next day shipping. If any of the products in the cart are not in stock, then only the Standard shipping option should be available.

I'm fairly sure I need to use the 'woocommerce_available_shipping_methods' filter as shown in this similar question / answer here : Hide Shipping Options Woocommerce , however I'm totally in the dark with regards how to check the stock level of each cart item.

Any pointers would be hugely appreciated.

¿Fue útil?

Solución

I've sorted this problem out now. My solution is definitely not suitable for everyone but it may help someone out.

I'm using this table rate shipping plugin for woocommerce : http://codecanyon.net/item/table-rate-shipping-for-woocommerce/3796656?WT (in case you want to replicate the way this works)

I'm indebted to the answer in this question: Hide Shipping Options Woocommerce

The code is basically copied from that but set up to check the stock quantity for the product.

This code DOES NOT take into account whether or not backorders are allowed, it literally checks if the stock quantity is > 0 and the cart quantity <= stock quantity. Basically if the product exists at the warehouse, next day shipping is available at checkout, if not it's removed and only Standard shipping is available.

/* !Hide Shipping Options Woocommerce */

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( $available_methods ) {

// use the function check_cart_for_oos() to check the cart for products with 0 stock.
if ( check_cart_for_oos() ) {

    // remove the rate you want
    unset( $available_methods['table_rate_shipping_next-day'] ); // Replace "table_rate_shipping_next-day" with "table_rate_shipping_your-identifier".
}

// return the available methods without the one you unset.
return $available_methods;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top