Skip to content

Early-bird lifetime licence: $199 once, for the first 200 buyers only. See the offer

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.

  • Type PHP
  • Runs Everywhere (runs as WordPress loads)
  • Needs WooCommerce
  • Category WooCommerce
  • Tested with WordPress 7.1, WooCommerce 11.1
PHP
<?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

Move your snippets over this afternoon.

Importing changes nothing until you switch over, and your old shortcodes keep working.