Skip to content

Instantly share code, notes, and snippets.

@kartikparmar
Created August 30, 2019 08:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kartikparmar/e632be7cd1be8a6c06e3ea608c153721 to your computer and use it in GitHub Desktop.
Save kartikparmar/e632be7cd1be8a6c06e3ea608c153721 to your computer and use it in GitHub Desktop.
Automatically adding the gift product to cart when specified criteria match
<?php
/*
* Automatically adding gift product to the cart
* Click on Add to Cart of Product A(under category cricket bat) will automatically add Gift A to cart
* Click on Add to Cart of Product B(under category cricket bat) will automatically add Gift A to cart
* Click on Add to Cart of Gift A will not automatically add Gift A to cart
*/
function aaptc_add_product_to_cart( $item_key, $product_id ) {
$product_category_id = 17; // cricket bat category id
$product_cats_ids = wc_get_product_term_ids( $product_id, 'product_cat' );
$free_product_id = 122; // Product Id of the free product which will get added to cart
if ( ! is_admin() && in_array( $product_category_id, $product_cats_ids ) && $free_product_id != $product_id ) {
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
WC()->cart->add_to_cart( $free_product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $free_product_id );
}
}
}
add_action( 'woocommerce_add_to_cart', 'aaptc_add_product_to_cart', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment