WordPress Snippets

WooCommerce – Add Complimentary/Free/Giveaway Product To Cart Programmatically

20 August 2021

Add a complimentary product:

Add this snippet ( update product id and product ids to exclude ):

/**
* @snippet Add Complimentary Product To Cart Programmatically - WooCommerce
* @author Prosvit Design Team
* @compatible WooCommerce 4.0.1
* @website http://prosvit.design
*/
add_filter('template_redirect', 'prosvit_add_complimentary_product_to_cart');
function prosvit_add_complimentary_product_to_cart()
{
// if admin - do nothing
if (is_admin()) return;
// if cart empty - do nothing
if (sizeof(WC()->cart->get_cart()) == 0) return;
$product_id = 15; // replace with your own complimentary product id
$product_ids_to_exclude = array(32); // Product ids to exclude - complimentary product will not be added with these products
$found = false;
$exclude = false;
// check if complimentary product already in cart and there are no exclusion products
foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
$_product = $values['data'];
if (in_array($_product->get_id(), $product_ids_to_exclude)) {
$exclude = true;
}
if ($_product->get_id() == $product_id) {
$product_id_cart_item_key = $cart_item_key;
$found = true;
}
}
// if complimentary product not found and there are no exclusions, add complimentary product
if (!$found && !$exclude) {
WC()->cart->add_to_cart($product_id);
wc_print_notice('Complimentary Product was added to the Cart!', 'notice');
}
// check for rough edges - only complimentry product in cart, clear cart
if (sizeof(WC()->cart->get_cart()) == 1 && $found) {
WC()->cart->empty_cart();
}
// check for rough edges - if exclusion product was added after complimentry product to cart, remove complimentary product
if ($found && $exclude) {
WC()->cart->set_quantity($product_id_cart_item_key, 0);
}
}

Does this snippet (still) work?

Please let us know in the comments if everything worked as expected. We would be happy to revise the snippet if you report otherwise (please provide screenshots).

Leave a Reply

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

Some of Our Clients

Join clients who enjoy 96% satisfaction

Schedule a Free Strategy Call with a WordPress Expert