WooCommerce:給第一次下單的新客户分發專屬優惠券

正在查看 1 個帖子:1-1 (共 1 個帖子)
  • 作者
    帖子
  • 詩語
    管理員
    • 文章數量: 5,925
    @feibisi
    樓主

    能用代碼的就儘量不用插件,為新的 WooCommerce 客户申請優惠券 ,請遵循以下步驟: –

    1 、在應用下面​​的代碼前,你必須創建一個新的優惠券。我創建了一個新的優惠券名稱’firstlove「

    2 、現在,您可以下面複製並粘貼代碼到你的主題的 functions.php

    /**
    * Frontend validate new customer only coupon code
    * hook: woocommerce_after_checkout_validation
    */
    add_action('woocommerce_after_checkout_validation','check_new_customer_coupon', 0);
    
    function check_new_customer_coupon(){
    global $woocommerce;
    // you might change the firstlove to your coupon
    $new_cust_coupon_code = 'firstlove';
    
    $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;
    }
    }
    
    }

    3 、如果你添加成功了,那麼現在可以嘗試註冊一個新用户然後去後台下單試試。

    如果上面的代碼不能滿足您的要求,您可以隨意修改。

    原文:https://www.techiecorner.com/3421/woocommerce-coupon-for-new-customer-first-order-only/

正在查看 1 個帖子:1-1 (共 1 個帖子)
  • 哎呀,回覆話題必需登錄。

話題信息

  • 當前位於:WooCommerce
  • 0 條回覆
  • 1 個參與人
  • 最後回覆:<a href="https://bbs.weixiaoduo.com/users/feibisi/" title=" 查看詩語的個人資料" class="bbp-author-link"><span class="bbp-author-name"> 詩語</span></a>
  • 上次活動:<a href="https://bbs.weixiaoduo.com/topic/17850/" title="WooCommerce:給第一次下單的新客户分發專屬優惠券">9 年、 1 月前</a>