Purchase One, Get One (BOGO)

You want a product to be automatically added to your basket when you add another product with a specific ID  (also known as “BOGO”).

If you want to give this second thing totally free, its price should be 0. Alternatively, you might have a defined retail price. In case you wish to conceal this free product from the store and just provide it as a gift once the first one is put in the cart, it should also be set to “hidden” from the catalog.

In addition, the given item must disappear from the Cart if you remove product 1.


add_action( 'template_redirect','clikresults_add_gift_if_id_in_cart' );

function clikresults_add_gift_if_id_in_cart() {

	if ( is_admin() ) return;
	if ( WC()->cart->is_empty() ) return;

//NOTE: replace xxx and yyy with your own product ID
	$product_bought_id = xxx;
	$product_gifted_id = yyy;

	// see if product id in cart
	$product_bought_cart_id = WC()->cart->generate_cart_id( $product_bought_id );
	$product_bought_in_cart = WC()->cart->find_product_in_cart( $product_bought_cart_id );

	// see if gift id in cart
	$product_gifted_cart_id = WC()->cart->generate_cart_id( $product_gifted_id );
	$product_gifted_in_cart = WC()->cart->find_product_in_cart( $product_gifted_cart_id );

	// if not in cart remove gift, else add gift
	if ( ! $product_bought_in_cart ) {
		if ( $product_gifted_in_cart ) WC()->cart->remove_cart_item( $product_gifted_in_cart );
	} else {
		if ( ! $product_gifted_in_cart ) WC()->cart->add_to_cart( $product_gifted_id );
	}
}