If WooCommerce Cart items are on backorder do not apply coupon

∥☆過路亽.° 提交于 2019-12-24 09:54:03

问题


So far this is what I've got:

add_filter('woocommerce_coupon_is_valid','coupon_always_valid',99,2);
function coupon_always_valid($valid, $coupon){
    global $woocommerce;
    $valid = true;
    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
       // if($values['data']->backorders_allowed()){ //check if backorders are allowed on this product
            // get the stock quantity - returns the available amount number
            $stock_info = $values['data']->get_stock_quantity();

            if($stock_info < 1){
                $vaild = false;

                break;
            }
        }
    // give error message...

    return $valid ; 
}

I don't understand why this option is not built into woocommerce to begin with. We want to blow out what we have in inventory but also take backorders on our products but, we do not want to give a discount to any backorders.

Any help would be appreciated.


回答1:


There is a typo error in your code for $vaild = false; (wrong variable name should be $valid) and an exta } as you have commented an if statement, causing the error.

Also below, I have upgraded your code to a more actual version (replacing global $woocommerce and $woocommerce->cart by WC()->cart):

add_filter( 'woocommerce_coupon_is_valid', 'coupon_always_valid', 99, 2 );
function coupon_always_valid( $valid, $coupon ){

    $valid = true;

    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // if($values['data']->backorders_allowed()){ //check if backorders are allowed on this product
        // get the stock quantity - returns the available amount number
        $stock_info = $cart_item['data']->get_stock_quantity();

        if( $stock_info < 1 ){
            $valid = false; ## <== HERE a typo error
            break;
        }
        // } ## <== HERE commented
    }
    return $valid ;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Now this code should work without errors



来源:https://stackoverflow.com/questions/45641987/if-woocommerce-cart-items-are-on-backorder-do-not-apply-coupon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!