如何解决仅当购物车中有 2 个类别的商品时才禁止 WooCommerce 结帐
我有 3 个类别“其他”、“D 类”和“T 类”:
• 如果用户的购物车中有属于 3 个类别的产品,则接受付款。
• 如果用户的购物篮中有属于“类别 D”和“其他”的产品,则接受付款。
• 如果用户只有一个类别的产品,则接受付款
• 如果用户的购物车中有属于“T 类”和“D 类”的产品,则拒绝付款。
• 如果篮子是空的,则不应出现错误消息。
总而言之,只有当用户的购物篮中有“D 类”和“T 类”产品时,才应拒绝付款。
这是我的代码:
function verifierproduitpanier(){
$cat_is_catD = false;
foreach (WC()->cart->get_cart() as $cart_item_key=>$cart_item){
$product = $cart_item['data'];
if (has_term('categorieD','product_cat',$product->id)) {
$cat_is_catD = true;
}
$cat_is_catT = false;
if (has_term('categorieT',$product->id)) {
$cat_is_catT = true;
}
$cat_is_other = false;
if (has_term('autre',$product->id)) {
$cat_is_other = true;
}
}
if ($cat_is_catD && $cat_is_catT && !$cart_is_other){
wc_add_notice(sprintf('<p>Les produits sélectionnés ne sont pas disponibles</p>'),'error');
}
}
add_action( 'woocommerce_check_cart_items','verifierproduitpanier' );
当我拥有属于“D 类”和“T 类”的商品时,我会收到一条弹出的错误消息,但问题是当我从“D 类”中删除产品并单击“取消”按钮时错误消息不再出现,付款已被接受。
有什么帮助吗?
解决方法
尝试使用以下重新访问的代码,如果只有属于类别 D 和 T 的项目,则该代码将不允许购买:
add_action( 'woocommerce_check_cart_items','check_products_in_cart' );
function check_products_in_cart(){
$taxonomy = 'product_cat'; // Product category taxonomy
$has_cat_d = $has_cat_t = $has_cat_o = false; // Initializing
// Loop through cart items
foreach (WC()->cart->get_cart() as $cart_item){
if ( has_term('categorieD',$taxonomy,$cart_item['product_id'] ) ) {
$has_cat_d = true;
}
elseif ( has_term('categorieT',$cart_item['product_id'] ) ) {
$has_cat_t = true;
}
elseif ( has_term('autre',$cart_item['product_id'] ) ) {
$has_cat_o = true;
}
}
if ( $has_cat_d && $has_cat_t && ! $has_cat_o ){
wc_add_notice( __("The Selected products are not available.","woocommerce"),'error');
}
}
代码位于活动子主题(或活动主题)的functions.php 文件中。经测试有效。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。