保留Add to Cart按钮,阻止特定分类商品加购并显示提示通知
解决方案
要实现你的需求,你需要替换原有代码的逻辑——不再通过设置purchasable为false来禁用按钮,而是通过拦截加购动作并显示指定提示语。以下是修改后的完整代码:
// 检查商品是否属于目标分类的自定义函数 function check_for_defined_product_categories( $product_id ) { $targeted_terms = array( 't-shirts' ); // 替换为你需要限制的商品分类slug return has_term( $targeted_terms, 'product_cat', $product_id ); } // 拦截购物车添加动作,阻止目标分类商品加入并显示提示 add_filter( 'woocommerce_add_to_cart_validation', 'block_target_category_add_to_cart', 10, 3 ); function block_target_category_add_to_cart( $passed, $product_id, $quantity ) { // 检查当前商品是否属于目标分类 if ( check_for_defined_product_categories( $product_id ) ) { $passed = false; // 阻止加入购物车 // 添加提示语 wc_add_notice( 'Sorry, you can not buy this product at this time; please try later', 'error' ); } return $passed; } // 可选:在产品页面提前显示提示(按钮上方),让用户提前知晓 add_action( 'woocommerce_before_add_to_cart_button', 'display_target_category_notice' ); function display_target_category_notice() { global $product; $product_id = $product->get_parent_id() > 0 ? $product->get_parent_id() : $product->get_id(); if ( check_for_defined_product_categories( $product_id ) ) { echo '<div class="woocommerce-error" style="margin-bottom:1em;">Sorry, you can not buy this product at this time; please try later</div>'; } }
代码说明:
- 保留了你原有的分类检查函数
check_for_defined_product_categories,只需修改$targeted_terms里的分类slug即可适配你的需求。 woocommerce_add_to_cart_validation过滤器会在商品加入购物车前触发验证,返回false直接阻止加购动作,同时通过wc_add_notice添加WooCommerce原生风格的错误提示。- 可选的
display_target_category_notice函数会在产品页面的加购按钮上方提前显示提示,避免用户点击后才发现无法加购,提升体验。 - 原有代码中
woocommerce_is_purchasable相关的过滤已移除,这样加购按钮会正常显示,不会被隐藏或禁用。
内容的提问来源于stack exchange,提问作者AdleyH
相关产品推荐
相关产品推荐

