Skip to content

Instantly share code, notes, and snippets.

@goranefbl
Created March 25, 2025 10:54
Show Gist options
  • Save goranefbl/547dbc52db6bed7b85179ed9fa964e47 to your computer and use it in GitHub Desktop.
Save goranefbl/547dbc52db6bed7b85179ed9fa964e47 to your computer and use it in GitHub Desktop.
wpgens auto apply coupon when product is added to cart
<?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