【问题标题】:Disallow WooCommerce checkout only when items from 2 categories are in cart仅当 2 个类别的商品在购物车中时才允许 WooCommerce 结帐
【发布时间】:2021-02-10 17:11:04
【问题描述】:

我有 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 类”中删除产品并单击“取消”按钮时错误消息不再出现,付款被接受。

有什么帮助吗?

【问题讨论】:

    标签: php wordpress woocommerce cart taxonomy-terms


    【解决方案1】:

    尝试使用以下重新访问的代码,仅当只有属于 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 文件中。经过测试并且可以工作。

    【讨论】:

    • 谢谢您的回复,但是如果我的购物车中有属于D类和T类的物品,我希望拒绝付款,如果我有属于3类的物品,则接受付款
    • @w.a 我的代码通常会这样做:当您的所有 3 个类别中都有项目时,它会接受结帐(我已经测试过并且它是这样工作的)......现在你的问题真的不清楚......所以首先编辑你的质疑和澄清事情。完成后在此处通知我。
    • 好的,谢谢,我编辑了我的问题,希望我更清楚
    猜你喜欢
    • 2017-01-31
    • 1970-01-01
    • 2019-01-27
    • 2021-01-17
    • 1970-01-01
    • 2019-03-02
    • 2019-10-20
    • 1970-01-01
    • 2020-01-12
    相关资源
    最近更新 更多