Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* @Title: Woocommerce Add a product to the cart programmatically
* @Author: Mina Pansuriya
* @Website: http://minapansuriya.com
* @Blog URL: http://minapansuriya.com/woocommerce-add-a-product-to-the-cart-programmatically/
*/
add_action( 'template_redirect', 'pbs_woo_add_gift_product_to_the_cart' );
function pbs_woo_add_gift_product_to_the_cart() {
$isAddGiftF = false;
if( is_cart() || is_checkout() )
{
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item )
{
$product = $cart_item['data'];
// If Product is THE product, add free gift
if($product->id == "331")
{
$isAddGiftF = true;
}
else if($product->id == "15722")
{
// If gift is already exist in the cart, don't add it again
$isAddGiftF = false;
}
}
if($isAddGiftF)
{
// Here First Parameter is Product Id and second partmeter is no. of products
WC()->cart->add_to_cart( 15722, 1 );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment