Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.