问题
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