WooCommerce Example Cart Restrictions

We have a “Trial Product” in our WooCommerce store which needs to be the only item in the cart during checkout due to shipping requirements (and because it doesn’t make sense to order a trial if you’re also going to order the actual product).

To make this clear to the customer, I’ve restricted what can be added to the cart in specific situations:

1) If the “Trial Product” is already in the cart, additional products should not be added. WooCommerce will instead display a notice asking the customer to remove the “Trial Product” from their cart if they wish to add different products.

2) If products are already in the cart, and the customer attempts to add the “Trial Product”, a notice will display asking the customer to remove the other items from their cart first.

Here’s what the code looks like:

<?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 );

About Devin

I'm a WordPress developer based in Austin, Texas. I run a little theme shop called DevPress and work for a startup called Nano. Find me on twitter @devinsays.

Leave a Reply