php 阻止客户添加某个类别的产品并显示通知

kupeojn6  于 2023-01-12  发布在  PHP
关注(0)|答案(1)|浏览(99)

我试图找到一个代码,以防止客户将特定类别的产品添加到购物车中,并显示一个通知“对不起,您现在不能购买此产品;请稍后再试”
我发现下面的代码,但它完全隐藏添加到购物车按钮,我不希望它发生。它应该显示添加到购物车按钮,但不允许项目添加到购物车。

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

希望你能帮助我解决这个问题。非常感谢!

  • 阻止将产品(属于特定类别)添加到购物车
  • 显示通知:“对不起,您此时不能购买此产品;请稍后再试”
  • 不隐藏添加到购物车按钮
gab6jxml

gab6jxml1#

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

相关问题