简体   繁体   中英

Prevent customers from adding products from a certain category and show notice

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM