WooCommerce – How to offer a free product with the purchase of certain products

Let’s say you running an offer where you want to give away a free product when a certain product or set of products is added to the cart.

Given how flexible and customizable WooCommerce is, everything is possible. Let’s see how we can accomplish this task.

<?php
/**
 * Maybe add offer product to the cart.
 */
function pj_maybe_add_products_to_cart() {
	// Add the product ID which have to be in cart for the offer to be applied.
	$products_should_be_in_cart = array( 3005 );
	// Free products which will be automatically added to cart.
	$free_products = array( 2005 );

	$items            = WC()->cart->get_cart();
	$products_in_cart = wp_list_pluck( $items, 'product_id' );
	$not_in_cart      = array_diff( $products_should_be_in_cart, $products_in_cart );

	// If all the required products are in the cart, then add all the offered products to cart
	// and set a custom data, that we will later in this function use to set the price to zero.
	if ( 0 === count( $not_in_cart ) ) {
		foreach ( $free_products as $product_id ) {

			// ensure offered product is not already in the cart.
			if ( ! in_array( $product_id, $products_in_cart, true ) ) {
				$item_data = array(
					// Tip: you can change the price of offered product here.
					'pj_offered_product_price' => 0, 
				);
				WC()->cart->add_to_cart( $product_id, 1, 0, array(), $item_data );
			}
		}
	}

	// Let's set the price.
	$items = WC()->cart->get_cart();
	foreach ( $items as $hash => $value ) {
		if ( isset( $value['pj_offered_product_price'] ) ) {
			$value['data']->set_price( $value['pj_offered_product_price'] );
		}
	}
}

add_action( 'woocommerce_before_calculate_totals', 'pj_maybe_add_products_to_cart' );

You need to add this code to the functions.php of your active theme. And you need to change the value of two variables: $products_should_be_in_cart variable and $free_products.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Up Next:

WooCommerce - How to calculate sum of all the sales ever done on the store?

WooCommerce - How to calculate sum of all the sales ever done on the store?