我目前正在为woocommerce开发一个插件,如果购物车的总数介于两个值之间,请使用以下代码添加折扣代码:
add_action('woocommerce_before_cart', 'woobd_add_discount_if_enabled');
function woobd_add_discount_if_enabled()
{
global $woocommerce;
if ($woocommerce->cart->cart_contents_total >= 10
&& $woocommerce->cart->cart_contents_total <= 100
) {
$woocommerce->cart->add_discount('layer1_discount');
} else {
$woocommerce->cart->remove_coupons('layer1_discount');
$woocommerce->cart->calculate_totals();
}
}
以上工作正常,但是我想添加另一个if语句,它增加了另外两个值:
add_action('woocommerce_before_cart', 'woobd_add_discount_if_enabled');
function woobd_add_discount_if_enabled()
{
global $woocommerce;
if ($woocommerce->cart->cart_contents_total >= 10
&& $woocommerce->cart->cart_contents_total <= 100
) {
$woocommerce->cart->add_discount('layer1_discount');
} else {
$woocommerce->cart->remove_coupons('layer1_discount');
$woocommerce->cart->calculate_totals();
}
if ($woocommerce->cart->cart_contents_total >= 100
&& $woocommerce->cart->cart_contents_total <= 200
) {
$woocommerce->cart->add_discount('layer2_discount');
} else {
$woocommerce->cart->remove_coupons('layer2_discount');
$woocommerce->cart->calculate_totals();
}
}
由于某种原因,只检测到第二个if语句,完全忽略第一个。上面有什么明显的错误吗?
答案 0 :(得分:1)
也许如果你将两个单独的语句改为if,elseif,else - 它就可以了。
add_action('woocommerce_before_cart', 'woobd_add_discount_if_enabled');
function woobd_add_discount_if_enabled()
{
global $woocommerce;
if ($woocommerce->cart->cart_contents_total >= 10
&& $woocommerce->cart->cart_contents_total <= 100
) {
$woocommerce->cart->add_discount('layer1_discount');
} elseif ($woocommerce->cart->cart_contents_total >= 100
&& $woocommerce->cart->cart_contents_total <= 200
) {
$woocommerce->cart->add_discount('layer2_discount');
} else {
$woocommerce->cart->remove_coupons('layer1_discount');
$woocommerce->cart->remove_coupons('layer2_discount');
$woocommerce->cart->calculate_totals();
}
}