Automatically applies a WooCommerce coupon when a customer visits any page with a ?coupon= URL parameter. Perfect for email campaigns, affiliate links, and ad landing pages where you want the discount applied without any manual input from the customer. Uses wc_format_coupon_code() to normalize the coupon code the WooCommerce way, and only runs on frontend page loads via template_redirect to avoid unnecessary overhead on admin, REST API, or cron requests.
add_action( 'template_redirect', 'auto_apply_coupon_from_url' );
function auto_apply_coupon_from_url() {
if ( empty( $_GET['coupon'] ) ) {
return;
}
if ( ! function_exists( 'WC' ) || is_null( WC()->cart ) ) {
return;
}
$coupon_code = wc_format_coupon_code( wp_unslash( $_GET['coupon'] ) );
if ( ! WC()->cart->has_discount( $coupon_code ) ) {
WC()->cart->apply_coupon( $coupon_code );
}
}