Skip to content

Instantly share code, notes, and snippets.

@goranefbl
Created September 5, 2024 13:15
Show Gist options
  • Save goranefbl/20ec02421259629fd8e489f699660a9b to your computer and use it in GitHub Desktop.
Save goranefbl/20ec02421259629fd8e489f699660a9b to your computer and use it in GitHub Desktop.
Auto add product to user cart if referral coupon is applied
<?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