Created
December 19, 2018 10:56
-
-
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.
This file contains 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
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