WooCommerce:给第一次下单的新客户分发专属优惠券

WooCommerce:给第一次下单的新客户分发专属优惠券


正在查看 1 个帖子:1-1 (共 1 个帖子)
  • 作者
    帖子
  • 诗语
    管理员
    • 文章数量: 5,866
    @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 个帖子)
  • 哎呀,回复话题必需登录。

未找到对应子版块?请直接在 [疑难杂症] 版块中发帖提问。

收藏纪念品


有奖活动

参与论坛社区问答,有机会获赠文派瓦普(Wapuu.com)手办模型。

话题信息

商业系统