Apply earned coupons automatically at checkout

Advocates often forget the coupons they earned. This snippet adds a logged-in customer’s unused referral coupons to their cart automatically.

Before you start: read Add code snippets safely. Written for version 4.4.12. Test it on a staging site with your checkout before using it on a live store.

Consider the built-in options first

  • Customers can see their unused coupons under My Account → Refer a Friend.
  • With WooCommerce Subscriptions, the plugin can apply referral coupons to renewals for you. See WooCommerce Subscriptions.
  • If advocates collect many small coupons, Stack rewards into one coupon may suit you better.

The snippet

add_action( 'woocommerce_cart_loaded_from_session', function ( $cart ) {
    if ( ! is_user_logged_in() || ( is_admin() && ! wp_doing_ajax() ) || $cart->is_empty() ) {
        return;
    }

    // Apply once per session, so customers can remove a coupon if they want to.
    if ( ! WC()->session || WC()->session->get( 'raf_coupons_auto_applied' ) ) {
        return;
    }
    WC()->session->set( 'raf_coupons_auto_applied', true );

    $email   = wp_get_current_user()->user_email;
    $coupons = get_posts( array(
        'post_type'   => 'shop_coupon',
        'post_status' => 'publish',
        'numberposts' => 10,
        'meta_query'  => array(
            array( 'key' => 'customer_email', 'value' => $email, 'compare' => 'LIKE' ),
            array( 'key' => 'usage_count', 'value' => '0' ),
        ),
    ) );

    foreach ( $coupons as $post ) {
        if ( strpos( $post->post_title, 'RAF-' ) !== 0 ) {
            continue;
        }
        $coupon  = new WC_Coupon( $post->post_title );
        $expires = $coupon->get_date_expires();
        if ( $expires && $expires->getTimestamp() < time() ) {
            continue;
        }
        if ( ! $cart->has_discount( $coupon->get_code() ) ) {
            $cart->apply_coupon( $coupon->get_code() );
        }
    }
} );

How it works

  • The first time a logged-in customer’s cart loads in a session, the snippet looks for their unused, unexpired RAF-… coupons and applies up to 10 of them.
  • It runs once per session. If the customer removes a coupon, it isn’t added back.
  • WooCommerce still checks each coupon’s rules, such as Minimum Order and product restrictions. A coupon that doesn’t fit the cart shows WooCommerce’s usual error.
  • If a coupon has Individual Use on, WooCommerce removes the other coupons. Turn off Individual Use in Advocate Reward if you want coupons to combine.

Check it worked

Log in as a customer with an unused referral coupon, add a product to the cart and open the cart. The coupon should be listed in the totals.

Related

Browse our plugins

Lightweight WooCommerce plugins built for speed. No bloat, no frameworks -- just clean code that works.

View all plugins
Stay in the loop

Get notified when we launch new plugins. No spam, just product updates.