Restricting cart items to be from the same product category in WooCommerce

↘锁芯ラ 提交于 2019-11-28 13:49:25

Making a custom function hooked in woocommerce_add_to_cart_validation filter hook is going to do the job in a much more simpler way, without any need to set an array of categories.

So your code will be much more faster and compact. Additionally you can display a custom notice to warn the customer.

This code will avoid adding to cart, if an item of a different category is in cart:

add_filter( 'woocommerce_add_to_cart_validation', 'add_to_cart_validation_callback', 10, 3 );
function add_to_cart_validation_callback( $passed, $product_id, $quantity) {
    // HERE set your alert text message
    $message = __( 'MY ALERT MESSAGE.', 'woocommerce' );

    if( ! WC()->cart->is_empty() ) {
        // Get the product category terms for the current product
        $terms_slugs = wp_get_post_terms( $product_id, 'product_cat' array('fields' => 'slugs'));

        // Loop through cart items
        foreach (WC()->cart->get_cart() as $cart_item ){
            if( ! has_term( $terms_slugs, 'product_cat', $cart_item['product_id'] )) {
                $passed = false;
                wc_add_notice( $message, 'error' );
                break;
            }
        }
    }
    return $passed;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and it works


Restricting cart items to be only from different product categories:

Replace in the function the condition:

if( ! has_term( $product_cats, 'product_cat', $cart_item['product_id'] )) { 

by

if( has_term( $product_cats, 'product_cat', $cart_item['product_id'] )) {
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!