How to automatically add a (free) product to users cart when they visit through referral link?

READ FIRST: This code needs to be added at the end of the functions.php file. If you are familiar with editing functions.php, feel free to continue reading. If you haven't done this before, adding this code in wrong place might bring the site down and the only way to access it is by editing functions.php file again via FTP. Feel free to contact us if you need help!

Lets say you want to reward users coming through referral link by giving them a free product. In order to do so, copy this code to theme functions.php file and change $product_id = 64 to your product ID. 

add_action( 'gens_raf_auto_apply_coupon', 'gens_add_product_to_cart' );
function gens_add_product_to_cart() {
		if(!isset($_COOKIE["gens_raf"])) {
			return false;
		$product_id = 64;
		$found = false;
		//check if product already in cart
		if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
			foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
				$_product = $values['data'];
				if ( $_product->id == $product_id )
					$found = true;
			// if product not found, add it
			if ( ! $found )
				WC()->cart->add_to_cart( $product_id );
		} else {
			// if no products in cart, add it
			WC()->cart->add_to_cart( $product_id );

Once you add this code, every user that comes through referral link will get that product added to his cart.

Still need help? Contact Us Contact Us