Apply a coupon from a link
Links like example.com/?coupon=SUMMER10 apply that coupon to the visitor’s cart, even before they add products. Perfect for newsletters and ads.
<?php
// Remember the code from the link.
add_action(
'wp_loaded',
static function () {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- A marketing link.
if ( empty( $_GET['coupon'] ) || ! WC()->session ) {
return;
}
$code = wc_format_coupon_code( sanitize_text_field( wp_unslash( $_GET['coupon'] ) ) );
if ( ! WC()->session->has_session() ) {
WC()->session->set_customer_session_cookie( true );
}
WC()->session->set( 'snipfire_coupon', $code );
}
);
// Apply it once the cart has something in it.
add_action(
'woocommerce_before_calculate_totals',
static function ( $cart ) {
if ( ! WC()->session || is_admin() && ! wp_doing_ajax() ) {
return;
}
$code = (string) WC()->session->get( 'snipfire_coupon' );
if ( '' === $code || $cart->is_empty() || $cart->has_discount( $code ) ) {
return;
}
WC()->session->set( 'snipfire_coupon', null );
$cart->apply_coupon( $code );
}
);
Good to know
The coupon itself (amount, expiry, limits) is set up as usual under Marketing > Coupons. Invalid codes show WooCommerce’s normal error.
In these packs
- WooCommerce: cart and checkout: Free-shipping progress, coupon links, quantity limits and a cleaner checkout.