Home » WooCommerce: “Buy One Get One” (Without a Plugin!)

WooCommerce: “Buy One Get One” (Without a Plugin!)

by Tutor Aspire

Case scenario: if you add a product ID to cart with a specific, you want another product automatically added to cart (Buy One Get One, or “BOGO”).

This second product should have price = 0 if you wish to completely give it away, or maybe a set sale price. It should also be set to “hidden” because maybe you want to hide this free product from the shop and only gift it when the first one is added to Cart.

Also, if you remove product 1, the gifted product should go away from the Cart too. So here follows the PHP snippet of course!

WooCommerce: add free gift to cart if product is added to cart

PHP Snippet: Add “Product Gift” to Cart if Product ID is Added to Cart (BOGO)

/**
 * @snippet       Buy 1 Get 1 - WooCommerce
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    Woo 3.8
 * @donate $9     https://tutoraspire.com
 */

add_action( 'template_redirect', 'tutoraspire_add_gift_if_id_in_cart' );

function tutoraspire_add_gift_if_id_in_cart() {

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

$product_bought_id = 32;
$product_gifted_id = 57;

// 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 );
}
}

You may also like