根据Woocommerce购物车小计自动为特定产品应用优惠券

时间:2019-03-01 23:30:17

标签: php wordpress woocommerce coupon discount

先参考这个问题:Apply a coupon programmatically in Woocommerce,然后再看这个问题:How to apply an automatic discount in WooCommerce based on cart total?

在这里填写新秀。当购物车中其他产品的小计为$ 40时,我需要将现有的优惠券自动应用于一种特定产品。而且我需要确保应用折扣不会由于将总金额降至40美元以下的门槛而取出优惠券,从而不会造成循环。

我不确定如何修改此代码来做到这一点:

add_action('woocommerce_before_checkout_process','add_discount_at_checkout');

function add_discount_at_checkout(){
global $woocommerce;
$minorder = 99;
if( $woocommerce->cart->get_cart()->cart_contents_total>$minorder){

 //APPLY COUPON HERE

}
}


1 个答案:

答案 0 :(得分:0)

首先,需要将目标优惠券代码设置为仅限于目标产品:

enter image description here

如果购物车小计(不包括此特定购物车项目)的总金额不超过$40,则以下代码将对特定购物车项目应用特定的优惠券(折扣):

add_action('woocommerce_before_calculate_totals', 'discount_based_on_total_threshold');
function discount_based_on_total_threshold( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Your settings
    $coupon_code      = 'summer'; // Coupon code
    $amount_threshold = 40; // Total amount threshold
    $targeted_product = 37; // Targeted product ID

    // Initializing variables
    $total_amount     = 0;
    $applied_coupons  = $cart->get_applied_coupons();
    $coupon_code      = sanitize_text_field( $coupon_code );
    $found            = false;

    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item ) {
        if( ! in_array( $targeted_product, array( $cart_item['product_id'], $cart_item['data']->get_id() ) ) ) {
            // Get the cart total amount (excluding the targeted product)
            $total_amount += $cart_item['line_total'] + $cart_item['line_tax'];
        } else {
            // Targeted product is found
            $found = true;
        }
    }

    // Applying coupon
    if( ! in_array($coupon_code, $applied_coupons) && $found && $total_amount >= $amount_threshold ){
        $cart->add_discount( $coupon_code );
    }
    // Removing coupon
    elseif( in_array($coupon_code, $applied_coupons) && ( $total_amount < $amount_threshold || ! $found ) ){
        $cart->remove_coupon( $coupon_code );
    }
}

代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。