在 WooCommerce 上有条件地应用生成的优惠券添加到购物车

Applying conditionally a generated coupon on WooCommerce add to cart

我目前正在使用 Gravity Forms(已启用引荐)。我在提交时使用挂钩根据优惠券模板(在我的 functions.php 中)生成随机优惠券。我的目标是让该优惠券在结帐页面自动应用于他们的订单。我已成功生成优惠券,但不太清楚如何应用它。仅供参考-我在用户体验中不使用购物车,所以产品页面 > 结帐。

如果有人能提供一些帮助,或者为我指明正确的方向,我将不胜感激。

// Generate Random Coupon  
function after_submission () {
$coupon_code = substr( "abcdefghijklmnopqrstuvwxyz123456789", mt_rand(0, 50) , 1) .substr( md5( time() ), 1); // Code
$coupon_code = substr( $coupon_code, 0,10); // create 10 letters coupon
$amount = '0'; // Amount
$discount_type = 'free_shipping'; // Type: fixed_cart, percent, fixed_product, percent_product

$coupon = array(
    'post_title' => $coupon_code,
    'post_content' => 'Free Shipping & Handling',
    'post_excerpt' => 'Free Shipping & Handling',
    'post_status' => 'publish',
    'post_author' => 1,
    'post_type'     => 'shop_coupon'
);

$new_coupon_id = wp_insert_post( $coupon );

// Add meta
update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
update_post_meta( $new_coupon_id, 'individual_use', 'yes' );
update_post_meta( $new_coupon_id, 'product_ids', '' );
update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
update_post_meta( $new_coupon_id, 'usage_limit', '1' );
update_post_meta( $new_coupon_id, 'expiry_date', '' );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'no' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );
update_post_meta( $new_coupon_id, 'exclude_sale_items', 'no' );
update_post_meta( $new_coupon_id, 'free_shipping', 'yes' );
update_post_meta( $new_coupon_id, 'product_categories', '' );
update_post_meta( $new_coupon_id, 'exclude_product_categories', '' );
update_post_meta( $new_coupon_id, 'minimum_amount', '' );
update_post_meta( $new_coupon_id, 'customer_email', '' );       

return $coupon_code;

}

// Gravity Forms Referral 
add_action( 'gform_after_submission_9', 'after_submission', 10, 2 );


// Add generated coupon to cart 
add_action( 'woocommerce_add_to_cart', 'apply_matched_coupons' );

function apply_matched_coupons() {
     if ( is_cart() || is_checkout() ) return;
     if ( WC()->cart->has_discount( $coupon_code ) ) return;
     WC()->checkout->add_discount( $coupon_code );
}

您需要在 WC 会话变量中设置创建的优惠券代码。那么你就可以轻松搞定了。

从 WooCommerce 3 开始,您的代码有点过时,有错误。请尝试以下操作:

// Early enable customer WC_Session
add_action( 'init', 'wc_session_enabler' );
function wc_session_enabler() {
    if ( is_user_logged_in() || is_admin() ) 
        return; 
        
    if ( isset(WC()->session) && ! WC()->session->has_session() ) { 
        WC()->session->set_customer_session_cookie( true ); 
    } 
}

// Utility function that generate a non existing coupon code (as each coupon code required to be unique)
function generated_counpon_code() {
    for ( $i = 0; $i < 1; $i++ ) {
        $coupon_code = strtolower( wp_generate_password( 10, false ) );

        // Check that the generated code doesn't exist yet
        if( coupon_exists( $coupon_code ) ) $i--; // continue
        else break; // Stop the loopp
    }
    return $coupon_code;
}

function coupon_exists( $coupon_code ) {
    global $wpdb;
    return $wpdb->get_var( $wpdb->prepare("SELECT COUNT(ID) FROM $wpdb->posts
        WHERE post_type = 'shop_coupon' AND post_name = '%s'", $coupon_code));
}

// Generate coupon and set code in customer WC session variable
function after_submission () {
    // Get a random unique coupon code
    $coupon_code = generated_counpon_code();

    // Get an empty instance of the WC_Coupon Object
    $coupon = new WC_Coupon();

    $coupon->set_code( $coupon_code );
    $coupon->set_discount_type( 'fixed_cart' );
    $coupon->set_description( __('Free Shipping & Handling') );
    $coupon->set_amount( 0 );
    $coupon->set_usage_limit( 1 );
    $coupon->set_free_shipping( 1 ); // <== Added back
    $coupon->set_individual_use( 1 );

    // Save coupon (data)
    $coupon->save();

    WC()->session->set( 'unique_coupon', $coupon_code );
}

// Gravity Forms Referral (hook)
add_action( 'gform_after_submission_9', 'after_submission', 10, 2 );


// Add generated coupon to cart
add_action( 'woocommerce_add_to_cart', 'apply_matched_coupons' );
function apply_matched_coupons() {
    if ( is_cart() || is_checkout() ) return;

    // Load coupon code
    $coupon_code = WC()->session->get( 'unique_coupon' );

    if ( $coupon_code && ! WC()->cart->has_discount( $coupon_code ) ) {
        WC()->cart->apply_coupon( $coupon_code ); // Apply coupon code
        WC()->session->__unset( 'unique_coupon' ); // remove session variable 
    }
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。已测试并有效。


文档WC_Coupon Class available setter and getter methods

相关:Create multiple coupons programmatically in WooCommerce 3+