簡體   English   中英

防止客戶添加某個類別的產品並顯示通知

[英]Prevent customers from adding products from a certain category and show notice

我試圖找到一個代碼來防止客戶將特定類別的產品添加到購物車並顯示通知“抱歉,您此時無法購買此產品;請稍后再試”

我在下面找到了一段代碼,但它完全隱藏了添加到購物車按鈕,我不希望它發生。 它應該顯示添加到購物車按鈕,但不允許將項目添加到購物車。

// 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;
}

希望你能幫我解決這個問題。 太感謝了!

  • 防止將產品(屬於特定類別)添加到購物車
  • 顯示通知:“抱歉,您暫時無法購買該商品,請稍后再試”
  • 不要隱藏加入購物車按鈕

在您的函數中添加以下代碼段。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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM