【问题标题】:Auto apply coupon only one time per user based on total spent in WooCommerce根据在 WooCommerce 中的总支出,每位用户仅自动应用一次优惠券
【发布时间】:2019-09-13 06:03:54
【问题描述】:

我想根据客户的总消费金额自动应用优惠券。此优惠券客户只需申请一次。

这是我迄今为止尝试过的,但我得到一个空白屏幕:

add_action( 'woocommerce_before_calculate_totals', 'loyalty_order_discount', 10, 1 );

function loyalty_order_discount( $order_id ) {
    global $woocommerce;

    $coupon = 'loyaltydiscount';
    $customer = new WC_Customer(get_current_user_id());
    $total_spent = 30;

    $order = wc_get_order( $order_id );

    foreach( $order->get_used_coupons( $customer ) as $coupon_name ){

        // Retrieving the coupon ID
        $coupon_post_obj = get_page_by_title($coupon_name, OBJECT, 'shop_coupon');
        $coupon_id = $coupon_post_obj->ID;

        $coupons_obj = new WC_Coupon($coupon_id);

        if( $coupons_obj == $coupon && $customer->get_total_spent() < $total_spent ){
            $woocommerce->cart->remove_coupon( $coupon );
        }
        elseif ( ! $coupons_obj == $coupon && $customer->get_total_spent() >= $total_spent){
            $woocommerce->cart->add_discount( $coupon );
        }
    }
}

感谢任何帮助。

【问题讨论】:

    标签: php wordpress woocommerce cart coupon


    【解决方案1】:

    首先,您需要为您的优惠券设置“每位用户的使用限制”选项为 1(并保存),例如:

    现在,以下重新访问的代码将仅在客户总支出达到规定金额时自动应用特定优惠券一次:

    add_action( 'woocommerce_before_calculate_totals', 'enable_customer_loyalty_discount', 10, 1 );
    function enable_customer_loyalty_discount( $cart ) {
        if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || ! is_user_logged_in() )
            return;
    
        if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
            return;
    
        //Your settings below
        $coupon_code = 'loyaltydiscount';
        $coupon_code = 'summer';
        $total_spent = 30;
    
        if( ! in_array( $coupon_code, $cart->get_applied_coupons() ) ) {
            $user_id  = get_current_user_id(); // User ID
    
            // Get the WC_Customer instance Object
            $customer = New WC_Customer( $user_id );
            $email    = $customer->get_billing_email(); // Billing email
    
            // If the user total spent has not reached the define amount, we exit
            if( $customer->get_total_spent() < $total_spent ) {
                return;
            }
    
            // Get the WC_Coupon instance Object
            $coupon = New WC_Coupon( $coupon_code );
    
            // If the coupon has already been used by the customer, we exit
            if( array_intersect( array($user_id, $email), $coupon->get_used_by() ) {
                return;
            }
    
            $cart->apply_coupon( $coupon_code );
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-06
      • 2019-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-03
      相关资源
      最近更新 更多