Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MinaPansuriya/6fd615b8726e8639e7e4df9fed7054ea to your computer and use it in GitHub Desktop.
Save MinaPansuriya/6fd615b8726e8639e7e4df9fed7054ea to your computer and use it in GitHub Desktop.
/**
* @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