I tried to find a code to prevent customers from adding products that are in a specific category to the cart and showing a notice "Sorry, you can not buy this product at this time; please try later"
I found a code below, but it completely hides add to cart button, and I don’t want it to happen. It should show add to cart button but does not allow items to be added to the cart.
// Custom conditional function that check for specific product categories
function check_for_defined_product_categories( $product_id ) {
$targeted_terms = array( 't-shirts' );
return has_term( $targeted_terms, 'product_cat', $product_id );
}
// Disable add to cart button (conditionally)
add_filter( 'woocommerce_variation_is_purchasable', 'woocommerce_is_purchasable_filter_callback', 10, 2 );
add_filter('woocommerce_is_purchasable', 'woocommerce_is_purchasable_filter_callback', 10, 2 );
function woocommerce_is_purchasable_filter_callback( $purchasable, $product ) {
$product_id = $product->get_parent_id() > 0 ? $product->get_parent_id() : $product->get_id();
if( check_for_defined_product_categories( $product_id ) ) {
$purchasable = false;
}
return $purchasable;
}
Hope you can help me with this issue. Thank you so much!
- Prevent products (belong to a specific category) to be added to cart
- Show notice: "Sorry, you can not buy this product at this time; please try later"
- Do not hide add to cart button
2
Answers
Add the following snippet in your functions.php