根据Woocommerce中的购物车项目自动应用/删除优惠券代码

问题描述 投票:3回答:2

如果购物车至少有2件商品,我想将优惠券代码应用到购物车。如果没有,那么优惠券将不适用并显示更改消息,如果已经申请,那么将显示成功消息这里是我的代码我尝试不工作,就像我想要的

add_action( 'woocommerce_before_calculate_totals','conditionally_auto_add_coupon', 30, 1 );

function conditionally_auto_add_coupon( $cart ) {

    if ( is_admin() && !defined('DOING_AJAX') ) return; // Exit

    // HERE set the coupon code (in lowercase)
    $coupon_code = 'mycode';

    $total_item = 0;

    if (WC()->cart->has_discount('mycode')) {

        foreach( $cart->get_cart() as $cart_item ){
          $total_item++;
        }
        if($total_item < 2){
            $cart->remove_coupon( $coupon_code );

            wc_add_notice( __('you have only 1 item in cart'), 'alert');
        }
        else{
            $cart->add_discount( $coupon_code );

            wc_add_notice( __('coupon added'), 'notice');
        }
    }
}

欢迎任何帮助。

php wordpress woocommerce cart coupon
2个回答
1
投票

请尝试以下方法:

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

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

    $coupon_code = 'summer'; // HERE set the coupon code (in lowercase)
    $applied     = in_array( $coupon_code, $cart->get_applied_coupons() ) ? true : false;
    $item_count  = sizeof( $cart->get_cart() );
    $total_item  = 0;

    // Remove coupon
    if ( $item_count < 2 && $applied ) {
        $cart->remove_coupon( $coupon_code );
        wc_clear_notices();
        wc_add_notice( __('You have only 1 item in cart'), 'error');
    }
    // Add coupon
    elseif ( $item_count >= 2 && ! $applied ) {
        $cart->apply_coupon( $coupon_code );
        wc_clear_notices();
        wc_add_notice( __('A coupon has been added'), 'notice' );
    }
}

代码位于活动子主题(或活动主题)的function.php文件中。经过测试和工作


0
投票

请使用"Smart Coupon For Woocommerce"插件实现自动优惠券功能,

请参考svn repo中的code

© www.soinside.com 2019 - 2024. All rights reserved.