Give referred friends a free product

Instead of, or as well as, a discount, you can give referred friends a free gift. This snippet adds a product to the friend’s cart when they open the cart or checkout after arriving through a referral link.

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

Create the gift product

  1. Go to Products → Add New.
  2. Create the gift with a Regular price of 0.
  3. Under Catalog visibility, choose Hidden, so it can’t be bought on its own.
  4. Publish it and note its ID. You’ll see it when you hover the product in Products.

Add the snippet

Change 64 to your product’s ID.

add_action( 'template_redirect', function () {
    $product_id = 64;

    if ( empty( $_COOKIE['gens_raf'] ) || ! function_exists( 'WC' ) || ! WC()->cart || ! WC()->session ) {
        return;
    }
    if ( ! is_cart() && ! is_checkout() ) {
        return;
    }
    if ( WC()->cart->is_empty() || WC()->session->get( 'raf_free_product_added' ) ) {
        return;
    }
    // Only new customers get the gift.
    if ( is_user_logged_in() && wc_get_customer_order_count( get_current_user_id() ) > 0 ) {
        return;
    }

    foreach ( WC()->cart->get_cart() as $item ) {
        if ( (int) $item['product_id'] === $product_id ) {
            return;
        }
    }

    WC()->cart->add_to_cart( $product_id );
    WC()->session->set( 'raf_free_product_added', true );
} );

How it works

  • The gift is added when a visitor with a referral cookie opens the cart or checkout with at least one other product in the cart.
  • It’s added once per session. If the friend removes it, it isn’t added back.
  • Logged-in customers who already have orders don’t get it. Guests can’t be checked before they enter their email, so a returning customer who isn’t logged in can still get it.
  • The gift isn’t tied to the plugin’s fraud checks. If the friend’s discount is removed at checkout, the gift stays in the cart.

Check it worked

Open an advocate’s referral link in a private window, add any product to the cart and open the cart. The gift should be in the cart at a price of 0.

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.