如何在 WooCommerce 中自动生成优惠券并将其应用到购物车?

How to auto generate a coupon in WooCommerce and apply it to the cart?

我已经搜索了网络和 Whosebug 上的许多页面。我正在尝试设置一个 WooCommerce 废弃的购物车流程,可以将 WooCommerce 中自动生成的优惠券添加到购物车。我已经删除了我发现的各种代码。我有它很粗糙但有点工作。我对 PHP 不太熟悉,所以很难让它正常运行。

当产品添加到购物车时,我在 WooCommerce 管理员中自动生成优惠券,它也应用在购物车页面上。然而,每次刷新页面时,都会生成更多优惠券并将其添加到购物车中。每次将产品添加到购物车时也会生成优惠券。

有没有办法限制优惠券只生成并使用一次?

我正计划从 Klaviyo 中重新创建的废弃购物车流程定向到 WooCommerce 购物车,其中将添加客户废弃购物车中的所有产品。我打算在 URL 后附加 https://example.com/cart?coupon-code=mycoupon

是否可以从 URL 变量(例如/mycoupon)触发优惠券创建?

请告诉我这是否可能?在我将生命的另一天浪费在这个项目上之前...哈哈

这是我到目前为止的代码。

function coupon_exists($coupon_code) {
    global $wpdb;

    $sql = $wpdb->prepare( "SELECT post_name FROM $wpdb->posts WHERE post_type = 'shop_coupon' AND post_name = '%s'", $coupon_code );

    $coupon_codes = $wpdb->get_results($sql);

    if (count($coupon_codes)> 0) {
        return true;
    }
    else {
        return false;
    }
} 

// Utility function that generate a non existing coupon code (as each coupon code has to be unique)
function random_coupon_code() {
    global $wpdb;
    
    // Get an array of all existing coupon codes
    $coupon_codes_check = $wpdb->get_col("SELECT post_name FROM $wpdb->posts WHERE post_type = 'shop_coupon'");
    
    for ( $i = 0; $i < 1; $i++ ) {
        $generated_code = strtolower( wp_generate_password( 15, false ) );
        
        // Check if the generated code doesn't exist yet
        if( in_array( $generated_code, $coupon_codes_check ) ) {
            $i--; // continue the loop and generate a new code
        } else {
            break; // stop the loop: The generated coupon code doesn't exist already
        }
    }
    return $generated_code;
}  

function generate_random_coupon($coupon_generated) {
    
// Set some coupon data by default
    $date_expires     = date('Y-m-d', strtotime('+1 days'));
    $discount_type    = 'fixed_cart'; // 'store_credit' doesn't exist
    $coupon_amount    = '10';

    $coupon = new WC_Coupon();
    
    // Generate a non existing coupon code name
    $coupon_code  = random_coupon_code();
    $coupon->set_code($coupon_generated);
    //the coupon discount type can be 'fixed_cart', 'percent' or 'fixed_product', defaults to 'fixed_cart'
    $coupon->set_discount_type($discount_type);
    //the discount amount, defaults to zero
    $coupon->set_amount($coupon_amount );
    $coupon->set_date_expires( $date_expires );

    //save the coupon
    $coupon->save();

    return $coupon_generated;
}


function hwn_add_programmatically_created_coupon_to_basket( $cart ) {
    
   if ( is_admin() && ! defined( 'DOING_AJAX' ) )
      return;
   if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
      return;
   $coupon_code  = random_coupon_code();
    
   if (!coupon_exists($coupon_code)) {
      generate_random_coupon($coupon_code);
   }        
   $applied_coupons  = $cart->get_applied_coupons();
   if( ! in_array($coupon_code, $applied_coupons)){
      $cart->add_discount( $coupon_code );
      wc_print_notices();
   }
   elseif( in_array($coupon_code, $applied_coupons)){
      $cart->remove_coupon( $coupon_code );
   }    
}
add_action('woocommerce_before_calculate_totals', 'hwn_add_programmatically_created_coupon_to_basket'); 

https://i.imgur.com/hzGfDkz.png

https://i.imgur.com/2yIlz1a.png

https://i.imgur.com/hfligL9.png

您可以使用 GET 方法从 URL 获取优惠券代码。试试下面的代码。您删除函数 random_coupon_code 因为现在您根据 URL.

生成优惠券代码
function coupon_exists( $coupon_code ) {
    global $wpdb;

    $sql = $wpdb->prepare( "SELECT post_name FROM $wpdb->posts WHERE post_type = 'shop_coupon' AND post_name = '%s'", $coupon_code );

    $coupon_codes = $wpdb->get_results($sql);

    if ( count( $coupon_codes ) > 0 ) {
        return true;
    } else {
        return false;
    }
} 

function generate_coupon($coupon_generated) {
    
    // Set some coupon data by default
    $date_expires     = date('Y-m-d', strtotime('+1 days'));
    $discount_type    = 'fixed_cart'; // 'store_credit' doesn't exist
    $coupon_amount    = '10';

    $coupon = new WC_Coupon();
    
    $coupon->set_code($coupon_generated);
    //the coupon discount type can be 'fixed_cart', 'percent' or 'fixed_product', defaults to 'fixed_cart'
    $coupon->set_discount_type($discount_type);
    //the discount amount, defaults to zero
    $coupon->set_amount($coupon_amount );
    $coupon->set_date_expires( $date_expires );

    //save the coupon
    $coupon->save();

    return $coupon_generated;
}

function hwn_add_programmatically_created_coupon_to_basket( $cart ) {
    
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;
    
    $coupon_code = ( isset( $_GET['coupon-code'] ) && $_GET['coupon-code'] != '' ) ? $_GET['coupon-code'] : '' ;

    if( $coupon_code == '' ){
        return;
    }

    $applied_coupons = $cart->get_applied_coupons();

    if( empty( $applied_coupons ) || ! in_array( $coupon_code, $applied_coupons ) ){
        if ( !coupon_exists( $coupon_code ) ) {
            generate_coupon( $coupon_code );
        }   
        $cart->add_discount( $coupon_code );
    }       

}
add_action('woocommerce_before_calculate_totals', 'hwn_add_programmatically_created_coupon_to_basket');

已测试并有效