Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harishankerr/83ff4c0797cd4b78eef3998769b1909d to your computer and use it in GitHub Desktop.
Save harishankerr/83ff4c0797cd4b78eef3998769b1909d to your computer and use it in GitHub Desktop.
Snippet to allow only products from a particular category to be added to the cart at a time.
add_filter( 'woocommerce_add_to_cart_validation', 'wc_limit_one_per_order', 10, 2 );
function wc_limit_one_per_order( $passed_validation, $product_id ) {
$terms = wp_get_post_terms( $product_id, 'product_cat' );
foreach ( $terms as $term ) $categories[] = $term->slug;
if ( in_array( 'clothes', $categories ) ) { // 'clothes' is the defined product category. Change this value to the slug of your choice.
return $passed_validation;
}
/* if ( 55 !== $product_id ) {
return $passed_validation;
}
*/
if ( WC()->cart->get_cart_contents_count() >= 1 ) {
wc_add_notice( __( 'Produts from the clothes category cannot be purchased with other products. Please, empty your cart first and then try again.', 'woocommerce' ), 'error' );
return false;
}
return $passed_validation;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment