Created
September 5, 2024 13:15
-
-
Save goranefbl/20ec02421259629fd8e489f699660a9b to your computer and use it in GitHub Desktop.
Auto add product to user cart if referral coupon is applied
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action( 'woocommerce_before_calculate_totals', 'wpgens_auto_apply_coupons_and_add_product', 10, 1 ); | |
function wpgens_auto_apply_coupons_and_add_product( $cart ) { | |
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) | |
return; | |
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) | |
return; | |
if(!is_user_logged_in()) | |
return; | |
$user_info = get_userdata(get_current_user_id()); | |
$user_email = $user_info->user_email; | |
$args = array( | |
'posts_per_page' => 10, | |
'post_type' => 'shop_coupon', | |
'post_status' => 'publish', | |
'meta_query' => array ( | |
'relation' => 'AND', | |
array ( | |
'key' => 'customer_email', | |
'value' => $user_email, | |
'compare' => 'LIKE' | |
), | |
array ( | |
'key' => 'usage_count', | |
'value' => '0', | |
'compare' => '=' | |
) | |
), | |
); | |
$raf_coupon_applied = false; | |
$coupons = get_posts( $args ); | |
if($coupons) { | |
foreach ( $coupons as $coupon ) { | |
if(!$cart->has_discount( $coupon->post_title ) && substr( $coupon->post_title, 0, 3 ) === "RAF" ){ | |
$cart->add_discount( $coupon->post_title ); | |
$raf_coupon_applied = true; | |
} | |
} | |
} | |
// If a RAF coupon was applied, add the product | |
if ($raf_coupon_applied) { | |
$product_id = 123; // Replace with your actual product ID | |
$product_in_cart = false; | |
foreach ($cart->get_cart() as $cart_item) { | |
if ($cart_item['product_id'] == $product_id) { | |
$product_in_cart = true; | |
break; | |
} | |
} | |
if (!$product_in_cart) { | |
$cart->add_to_cart($product_id); | |
wc_add_notice('A product has been automatically added to your cart based on your RAF coupon.', 'notice'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment