Skip to content

Instantly share code, notes, and snippets.

@emilushi
Last active May 8, 2019 20:41
Show Gist options
  • Save emilushi/699b70bf56c2c8d998a4bf3dea5ea59b to your computer and use it in GitHub Desktop.
Save emilushi/699b70bf56c2c8d998a4bf3dea5ea59b to your computer and use it in GitHub Desktop.
WooCommerce dont allow Subscription and Regular product on same checkout.
<?php
use WC_Subscriptions_Cart;
add_filter('woocommerce_add_to_cart_validation', function(){
//If WooCommerce Subscriptions is installed handle the things...
if (in_array('woocommerce-subscriptions/woocommerce-subscriptions.php', apply_filters('active_plugins', get_option('active_plugins')), true)) {
$cartContent = WC()->cart->get_cart();
if (is_array($cartContent) && ! empty($cartContent)) {
$cartContainsSubscription = WC_Subscriptions_Cart::cart_contains_subscription();
/** @var WC_Product|null|false $productToBeAdded */
$productToBeAdded = wc_get_product($product_id);
$productToBeAddedType = $productToBeAdded->get_type();
if (($cartContainsSubscription === true && $productToBeAddedType !== 'variable-subscription') || ($cartContainsSubscription === false && $productToBeAddedType === 'variable-subscription')) {
$passed = false;
wc_add_notice(__('You can not have "Subscription Product" and "Regular Product" in your cart at the same time.'), 'error');
}
}
}
return $passed;
}, 10, 2);
@emilushi
Copy link
Author

emilushi commented May 8, 2019

I once need to stop visitors to add Regular products and Subscription products at the same time on WooCommerce cart. And here is the solution.
In my case I had to prevent it for Variable Subscription products, thats why the product type on line 19 is set to variable-subscription, but you can extend the if condition to other options even if it isn't related to Subscription products...

You can add the above code on your theme functions or call it with your plugin if you are building one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment