Skip to content

Instantly share code, notes, and snippets.

@kartikparmar
Last active January 20, 2018 06:48
Show Gist options
  • Save kartikparmar/d8e0ee06b5dcba0eab4dc4d87ec66405 to your computer and use it in GitHub Desktop.
Save kartikparmar/d8e0ee06b5dcba0eab4dc4d87ec66405 to your computer and use it in GitHub Desktop.
Using this you can remove free product from cart when parent product is removed
<?php
/**
* Remove free product from cart when parent product is removed.
*/
function remove_product_from_cart() {
// Run only in the Cart or Checkout Page
if( is_cart() || is_checkout() ) {
$prod_to_remove = 13002; // Product ID of Free Product
$parent_product_id = 13901; // Product ID of Parent Product
$parent_pro_check = false;
// Check in the cart if Parent product is present or not
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'];
// Check to see if IDs match
if ( $parent_product_id == $prod_id ) {
// Get it's unique ID within the Cart
$parent_pro_check = true;
}
if ( $prod_to_remove == $prod_id ) {
$free_pro_cart_id = WC()->cart->generate_cart_id( $prod_id );
}
}
// If Parent product is not present then remove the free product.
if ( !$parent_pro_check ) {
// 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