mardi 4 août 2020

Applying conditionally a generated coupon on WooCommerce add to cart

I'm currently using Gravity Forms (with referral as lead enabled). I'm using a hook on submit to generate a random coupon based off of a coupon template (in my functions.php). My goal is to then have that coupon automatically applied to their order at the checkout page. I'm successfully able to generate the coupon, but can't quite figure out how to apply it. FYI- I do not use a cart in the user experience, so Product Page > Checkout.

If someone could provide some help, or point me in the right direction, I'd be grateful.

// 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 );
}



Aucun commentaire:

Enregistrer un commentaire