Skip to content

Instantly share code, notes, and snippets.

@mtruitt
Last active November 16, 2017 22:32
Show Gist options
  • Save mtruitt/152040e6b6497199ef80244a7fbfdcae to your computer and use it in GitHub Desktop.
Save mtruitt/152040e6b6497199ef80244a7fbfdcae to your computer and use it in GitHub Desktop.
Remove Products based on a specific product getting added.
<?php
function remove_products_from_cart( $cart_item_key ) {
// Products allowed with gift sub
$allowed_products = array( 230973 , 231122, 230510 );
// Gift Subscription Product ID
$gift_product_id = 230973;
// Lets get all the IDs in the cart
foreach (WC()->cart->get_cart() as $value) {
$cart_ids[] = $value['product_id'];
}
//Check cart IDs again gift product ID
if ( in_array( $gift_product_id, $cart_ids )) {
wc_add_notice(' Gift Subscriptions must be purchased individually. ');
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
$product_id = $cart_item['product_id'];
if ( !in_array( $product_id, $allowed_products ) ) {
WC()->cart->remove_cart_item( $cart_item_key );
}
}
}
}
add_action( 'woocommerce_add_to_cart', 'remove_products_from_cart' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment