Last active
July 10, 2023 21:12
-
-
Save daigo75/cf7f5edc6b83aa582a9c to your computer and use it in GitHub Desktop.
WooCommerce – Only allow certain product combinations in cart
This file contains hidden or 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
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!