Php 如果购物车包含特定的Woocommerce产品类别,则禁止添加到购物车

Php 如果购物车包含特定的Woocommerce产品类别,则禁止添加到购物车,php,wordpress,woocommerce,Php,Wordpress,Woocommerce,我的问题和代码直接基于这个问题- " 我有一个包含5个类别的商店。它是多供应商的,由于运输复杂,我只能销售一个特定类别(“油漆”)的产品当他们单独在购物车中时。因此,我需要防止在购物车包含绘画时将任何非绘画产品添加到购物车中,并显示错误消息,我需要防止将绘画产品添加到包含任何其他类别的购物车中,并禁用错误消息 我试图从Stackoverflow和其他地方找到的代码片段中拼凑出这段代码。逻辑似乎在我的大脑中起作用,但当我尝试实现代码(通过functions.php)时,它会阻止任何产品添加到购物车

我的问题和代码直接基于这个问题- " 我有一个包含5个类别的商店。它是多供应商的,由于运输复杂,我只能销售一个特定类别(“油漆”)的产品当他们单独在购物车中时。因此,我需要防止在购物车包含绘画时将任何非绘画产品添加到购物车中,并显示错误消息,我需要防止将绘画产品添加到包含任何其他类别的购物车中,并禁用错误消息

我试图从Stackoverflow和其他地方找到的代码片段中拼凑出这段代码。逻辑似乎在我的大脑中起作用,但当我尝试实现代码(通过functions.php)时,它会阻止任何产品添加到购物车中,除非购物车是空的。”

链接到问题-

我已经检查并修改了已接受的答案,以满足我的需要,但它似乎根本不起作用,因为我有相同的问题,只是与不同的类别有关(即气体而不是油漆),我的理解是,我只需要修改“has_术语”函数以使其工作,因为它只是指向特定类别的问题

//*** Prevent mixture of gas and other prods in same cart ***//
function dont_add_gas_to_cart_containing_other($validation, $product_id) {

// Set flag false until we find a product in gas
    $cart_has_gas = false;

// Set $cat_check true if a cart item is in gas cat
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {

        $product = $cart_item['data'];

        if (has_term('Gas', 'Gas Tanks & Accessories', $product->id)) {
            $cart_has_gas = true;
            // break because we only need one "true" to matter here
            break;
        }
    }

    $product_is_gas = false;
    if (has_term('Gas', 'Gas Tanks & Accessories', $product_id)) {
        $product_is_gas = true;
    }

// Return true if cart empty
    if (!WC()->cart->get_cart_contents_count() == 0) {
        // If cart contains gas and product to be added is not gas, display error message and return false.
        if ($cart_has_gas && !$product_is_gas) {
            wc_add_notice('Sorry, you can only purchase Helium Gas products on their own. To purchase this product, please checkout your current cart or empty your cart and try again', 'error');
            $validation = false;
        }
        // If cart contains a product that is not gas and product to be added is gas, display error message and return false.
        elseif (!$cart_has_gas && $product_is_gas) {
            wc_add_notice('Sorry, you can only purchase Helium Gas products on their own. To purchase this product, please checkout your current cart or empty your cart and try again', 'error');
            $validation = false;
        }
    }
    // Otherwise, return true.
    return $validation;
}

add_filter('woocommerce_add_to_cart_validation', 'dont_add_gas_to_cart_containing_other', 10, 2);

因为您为函数指定了类别名称,所以必须为函数指定一个slug,第二个参数应该是
'product\u cat'
,最后一个参数应该是
产品ID


所以第一个参数是气体类slug?这非常有效,非常感谢,但是我注意到我的“wc_添加_通知”消息没有显示欢迎您。您有两个条件
具有_term
。你们两个都换了吗?我确实换了,我已经测试了两种方式,除了显示的通知外,工作正常
$product = $cart_item['data'];

if( has_term( 'gas', 'product_cat', $product->get_id() ) ) {
    ......
}