首页 > 解决方案 > 仅当 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_cat',$product->id)) {
            $cat_is_catT = true;
        }
        
        $cat_is_other = false;

        if (has_term('autre', 'product_cat',$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 类”中删除产品并单击“取消”按钮时,错误消息没有出现更长的时间并接受付款。

有什么帮助吗?

标签: phpwordpresswoocommercecarttaxonomy-terms

解决方案


请尝试使用以下重新访问的代码,仅当只有属于 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', $taxonomy, $cart_item['product_id'] ) ) {
            $has_cat_t = true;
        }
        elseif ( has_term('autre', $taxonomy, $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 文件中。测试和工作。


推荐阅读