Skip to content

Instantly share code, notes, and snippets.

@kartikparmar kartikparmar/functions.php
Last active Feb 25, 2019

Embed
What would you like to do?
Removing free product when cart doesn't contains product of particular category.
<?php
/**
* Removing free product from cart when cart doensn't contains product of perticular category.
*/
function remove_product_from_cart() {
// Run only in the Cart or Checkout Page
if ( is_cart() || is_checkout() ) {
$product_category_id = 73; // ID of category
$prod_to_remove = 2115; // Product ID of Free Product
$cart_contains_category = false; // Default set to false : This means cart doesn't contains any product of perticular category
$free_pro_cart_id = "";
foreach ( WC()->cart->cart_contents as $prod_in_cart ) {
// Get the Variation or Product ID
$prod_id = ( isset( $prod_in_cart['variation_id'] ) && $prod_in_cart['variation_id'] != 0 ) ? $prod_in_cart['variation_id'] : $prod_in_cart['product_id'];
$product_cats_ids = wc_get_product_term_ids( $prod_id, 'product_cat' );
if ( in_array( $product_category_id, $product_cats_ids ) ){
$cart_contains_category = true; // cart has the product of particular category.
break;
}
}
if ( !$cart_contains_category ) { // remove free product if cart doesn't contain product of perticular category
$free_pro_cart_id = WC()->cart->generate_cart_id( $prod_to_remove );
// Remove it from the cart by un-setting it
unset( WC()->cart->cart_contents[ $free_pro_cart_id ] );
}
}
}
add_action( 'template_redirect', 'remove_product_from_cart' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.