Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daigo75/cf7f5edc6b83aa582a9c to your computer and use it in GitHub Desktop.
Save daigo75/cf7f5edc6b83aa582a9c to your computer and use it in GitHub Desktop.
WooCommerce – Only allow certain product combinations in cart
// Step 1 - Keep track of cart contents
add_action('wp_loaded', function() {
// This variable must be global, we will need it later. If this code were
// packaged as a plugin, a property could be used instead
global $allowed_cart_items;
// We decided that products with ID 737 and 832 can go together. If any of them
// is in the cart, all other products cannot be added to it
$restricted_cart_items = array(
737,
832,
);
// Use a separate cart instance, so that the one used by WooCommerce is unaffected
$cart = new WC_Cart();
foreach($cart->get_cart() as $item) {
if(in_array($item['data']->id, $restricted_cart_items)) {
$allowed_cart_items[] = $item['data']->id;
}
}
add_filter('woocommerce_is_purchasable', function($is_purchasable, $product) {
global $allowed_cart_items;
// If any of the restricted products is in the cart, any other must be made
// "not purchasable"
if(!empty($allowed_cart_items)) {
$is_purchasable = in_array($product->id, $allowed_cart_items);
}
return $is_purchasable;
}, 10, 2);
}, 10);
// Step 3 - Explain customers why they can't add some products to the cart
add_filter('woocommerce_get_price_html', function($price_html, $product) {
if(!$product->is_purchasable()) {
$price_html .= '<p>' . __('This product cannot be purchased together with "Product X" or "Product Y". If you wish to buy this product, please remove the other products from the cart.', 'woocommerce') . '</p>';
}
return $price_html;
}, 10, 2);
@friendorfoley
Copy link

This worked to stop products being added to the cart together but I have removed step three because in my scenario the messaging shows up on every product where as I would just need a single error message to display at the time of trying to add Product X & Y to the cart together.

This is an extremely helpful bit of code! Thank you very much :)

@daigo75
Copy link
Author

daigo75 commented May 5, 2020

Indeed, the script is meant to be a proof of concept. It can be extended and optimised as you need, for example to give a cleaner user experience. I'm glad that you found it useful. 👍

@friendorfoley
Copy link

Absolutely, it's gotten me on my way and I'm learning so it's now up to me to implement what I need :) thanks again!

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