Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Restricts which items can be added to cart based on whether a specific item is already in the cart or being added to the cart.
<?php
/**
* WooCommerce code snippet that restricts which items can be added to cart:
*
* 1) The $trial_product should not be added to cart if existing items are in the cart.
* 2) Other products should not be added to cart if $trial_product is already in cart.
*/
function example_cart_filtering( $passed_validation, $product_id ) {
// ID of the trial product
$trial_product_id = 9344;
// If cart is empty, no need for additional validation.
if ( WC()->cart->is_empty() ) {
return $passed_validation;
}
// If trial product is being added to cart, existing products should be removed.
if ( $trial_product_id === $product_id ) {
$notice = sprintf(
// Translators: Placeholder is for cart url.
__( 'Trial Product can not be purchased with other products. Please empty your <a href="%s">existing cart</a>.' ),
esc_url( wc_get_cart_url() )
);
wc_add_notice( $notice, 'notice' );
return false;
}
// If trial product is in cart, additional products should not be added.
$products = WC()->cart->get_cart_contents();
foreach ( $products as $product => $values ) {
$product_id = $values['data']->get_id();
if ( $trial_product_id === $product_id ) {
$notice = sprintf(
// Translators: Placeholder is for cart url.
__( 'The Trial Product can not be ordered with other items.<br> Please remove the Trial Product from <a href="%s">your cart</a> if you wish to make other purchases.' ),
esc_url( wc_get_cart_url() )
);
wc_add_notice( $notice, 'notice' );
return false;
}
}
// Trial Product is not in cart or being added.
return $passed_validation;
}
add_filter( 'woocommerce_add_to_cart_validation', 'example_cart_filtering', 100, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment