skip to Main Content

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


  1. Chosen as BEST ANSWER
    function exclude_products_from_cart($cart_item_key, $product_id) {
    if( has_term( array( 'accessories'), 'product_cat', $product_id )) {
        WC()->cart->remove_cart_item($cart_item_key);
        wc_add_notice(__('Sorry, this product is not available now; please try tommorrow','woocommerce'),'error');
        add_filter( 'wc_add_to_cart_message_html', '__return_false' );
        }
    }
    add_action('woocommerce_add_to_cart','exclude_products_from_cart',10,2);
    

  2. Add the following snippet in your functions.php

    function exclude_products_from_cart($cart_item_key, $product_id) {
        //Add one or many categories you want to compare
        if( has_term( array( 'accessories'), 'product_cat', $product_id )) {
            WC()->cart->remove_cart_item($cart_item_key);
            wc_add_notice(__('Sorry, you can not buy this product at this time; please try later','woocommerce'),'notice'); // The name of the notice type - either error, success or notice
        }
    }
    add_action('woocommerce_add_to_cart','exclude_products_from_cart',10,2);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search