在我尝试找到基于美元金额的自动优惠券的解决方案时,我遇到了以下问题。首先是规则:
我已经能够使代码使用代码的第二个(2)规则。但是,第三条规则将不适用。我的代码如下。有什么想法吗?
// Add coupon when user views cart before checkout
add_action('woocommerce_before_cart_table', 'add_coupon_automatically');
add_action('woocommerce_before_checkout_form', 'add_coupon_automatically');
// Check if function? create it.
if (!function_exists('add_coupon_automatically')) {
function add_coupon_automatically() {
global $woocommerce;
$eleven = '20plus';
$four = '10plus';
$eleven_minimum = 179;
$four_minimum = 89;
if($woocommerce->cart->get_cart()->cart_contents_total>$eleven_minimum) {
// Apply 20plus
if (!$woocommerce->cart->add_discount( sanitize_text_field( $eleven )))
$woocommerce->add_message('20 Plus coupon (11%) automatically applied!');
$woocommerce->show_messages();
//Recalculate totals
$woocommerce->cart->calculate_totals();
} elseif ($woocommerce->cart->get_cart()->cart_contents_total<$eleven_minimum
&& $woocommerce->cart->get_cart()->cart_contents_total>$four_minimum) {
// Apply 10plus
if (!$woocommerce->cart->add_discount( sanitize_text_field( $four )))
$woocommerce->add_message('10 Plus coupon (4%) automatically applied!');
$woocommerce->show_messages();
//Recalculate totals
$woocommerce->cart->calculate_totals();
}
}
}
答案 0 :(得分:2)
以错误的方式进行。似乎最好的方法是将其基于购物车物品数量而不是价格。
新规则:
添加到child_theme/woocommerce/cart.php
global $count_cart_quantity;
$count_cart_quantity = $woocommerce->cart->cart_contents_count;
最后通过钩子申请优惠券
add_action('woocommerce_before_cart_table', 'discount_20');
function discount_20() {
global $woocommerce;
global $count_cart_quantity;
if ( $count_cart_quantity > 19 ) {
$coupon_code = '20plus';
if (!$woocommerce->cart->add_discount(sanitize_text_field($coupon_code))) {
$woocommerce->show_messages();
}
echo '<div classs"woocommerce_message"><strong>
You qualified for an 11% discount and it has been applied!</strong>
</div>';
}
}
add_action('woocommerce_before_cart_table', 'discount_10');
function discount_10() {
global $woocommerce;
global $count_cart_quantity;
if ( $count_cart_quantity < 20 && $count_cart_quantity > 9 ) {
$coupon_code = '10plus';
if (!$woocommerce->cart->add_discount(sanitize_text_field($coupon_code))) {
$woocommerce->show_messages();
}
echo '<div classs"woocommerce_message"><strong>
You qualified for an 4% discount and it has been applied!</strong>
</div>';
}
}
现在效果很好!
答案 1 :(得分:0)
你可以改变
$woocommerce->cart->get_cart()->cart_contents_total
到
$woocommerce->cart->cart_contents_total
那么你的功能就可以了。