# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [WooCommerce](https://wpide.com/library/category/woocommerce/)
- Requires: WooCommerce
- Tags: woocommerce, coupons, marketing
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/woo-coupon-from-url/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Apply a Coupon From a Link" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
