Created
March 25, 2025 10:54
-
-
Save goranefbl/547dbc52db6bed7b85179ed9fa964e47 to your computer and use it in GitHub Desktop.
wpgens auto apply coupon when product is added to cart
This file contains 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_add_to_cart', 'wpgens_auto_apply_coupons_on_add_to_cart', 10, 6 ); | |
function wpgens_auto_apply_coupons_on_add_to_cart( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) { | |
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) | |
return; | |
if ( ! is_user_logged_in() ) | |
return; | |
if ( WC()->cart === null ) | |
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' => '=', | |
), | |
), | |
); | |
$coupons = get_posts( $args ); | |
if ( $coupons ) { | |
foreach ( $coupons as $coupon ) { | |
if ( ! WC()->cart->has_discount( $coupon->post_title ) && substr( $coupon->post_title, 0, 3 ) === 'RAF' ) { | |
WC()->cart->add_discount( $coupon->post_title ); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment