Last active
April 8, 2020 00:48
-
-
Save kartikparmar/fc39177351aed9b2275e82b037e40663 to your computer and use it in GitHub Desktop.
Removing free product when cart doesn't contains product of particular category.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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