2016-06-29 5 views
0

Woocommerceでは、新規顧客が最初に注文した商品に20%の割引を適用する方法を探しています。 私はこれを行うにはwoocommerce_after_checkout_validationcheck_new_customer_couponの機能を使用することができますが、動作しないようです。顧客が最初に注文するために、プログラムでクーポンをWoocommerceに適用するにはどうすればよいですか?

function.php:

add_action('woocommerce_after_checkout_validation','check_new_customer_coupon', 0); 

function check_new_customer_coupon(){ 
    global $woocommerce; 
    // you might change the name of your coupon 
    $new_cust_coupon_code = 'test'; 

    $has_apply_coupon = false; 

    foreach (WC()->cart->get_coupons() as $code => $coupon) { 
     if($code == $new_cust_coupon_code) { 
      $has_apply_coupon = true; 
     } 
    } 

    if($has_apply_coupon) { 

     if(is_user_logged_in()) { 
      $user_id = get_current_user_id(); 

      // retrieve all orders 
      $customer_orders = get_posts(array(
        'meta_key' => '_customer_user', 
        'meta_value' => $user_id, 
        'post_type' => 'shop_order', 
        'numberposts'=> -1 
      )); 

      if(count($customer_orders) > 0) { 
       $has_ordered = false; 

       $statuses = array('wc-failed', 'wc-cancelled', 'wc-refunded'); 

       // loop thru orders, if the order is not falled into failed, cancelled or refund then it consider valid 
       foreach($customer_orders as $tmp_order) { 

        $order = wc_get_order($tmp_order->ID); 
        if(!in_array($order->get_status(), $statuses)) { 
         $has_ordered = true; 
        } 
       } 

       // if this customer already ordered, we remove the coupon 
       if($has_ordered == true) { 
        WC()->cart->remove_coupon($new_cust_coupon_code); 
        wc_add_notice(sprintf("Coupon code: %s is only applicable for new customer." , $new_cust_coupon_code), 'error'); 
        return false; 
       } 
      } else { 
       // customer has no order, so valid to use this coupon 
       return true; 
      } 

     } else { 
      // new user is valid 
      return true; 
     } 
    } 

} 

答えて

0

たぶん、あなたはサイト上でこのような何かを置くことによって回避策を行うことができます。

クーポンXXXXXXであなたの最初のcommande

のため20%オフを取得

https://docs.woothemes.com/document/coupon-management/

とクーポン管理では、ユーザー1人に制限を設けますか?

+0

このソリューションはすべてのお客様向けです。私はこの割引を新しいcostumersのためだけに利用したいと思っています。 –

関連する問題