Apply a Coupon From a Link
Lets you share links like yoursite.com/?coupon=SUMMER10 that apply the coupon automatically when the shopper adds to cart or visits the cart.
Opens WPIDE on
Code
add_action( 'wp_loaded', function () {
$param = 'coupon'; // Query parameter that carries the coupon code.
if ( is_admin() || empty( $_GET[ $param ] ) || ! function_exists( 'WC' ) ) { // phpcs:ignore WordPress.Security.NonceVerification
return;
}
$code = wc_format_coupon_code( sanitize_text_field( wp_unslash( $_GET[ $param ] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification
if ( '' === $code || ! WC()->session ) {
return;
}
if ( ! WC()->session->has_session() ) {
WC()->session->set_customer_session_cookie( true );
}
WC()->session->set( 'wpide_pending_coupon', $code );
} );
add_action( 'woocommerce_cart_loaded_from_session', function ( $cart ) {
if ( ! WC()->session ) {
return;
}
$code = WC()->session->get( 'wpide_pending_coupon' );
if ( ! $code || $cart->is_empty() ) {
return;
}
if ( ! $cart->has_discount( $code ) ) {
$cart->apply_coupon( $code );
}
WC()->session->set( 'wpide_pending_coupon', null );
} );
Notes
The coupon must exist in WooCommerce > Marketing > Coupons. Change $param to use a different query parameter.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.