Checking cart items for a product category in Woocommerce

一世执手 提交于 2019-12-06 07:11:16

To check product categories in cart items using WordPress has_term() conditional function, you need to use $cart_item['product_id'] instead to handle checking product categories in product variations too.

This way it check in the parent variable product for the product category as product variation type doesn't handle any custom taxonomy. So now it will work for all cases.

So your revisited code will be:

add_action('woocommerce_before_cart', 'check_product_category_in_cart');
function check_product_category_in_cart() {
    // HERE set your product categories in the array (can be IDs, slugs or names)
    $categories = array('downloads');
    $found      = false; // Initializing

    // Loop through cart items      
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // If product categories is found
        if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
            $found = true; // Set to true
            break; // Stop the loop
        }
    }

    // If any defined product category is found, we display a notice
    if ( $found ) {
        wc_print_notice( __('Product Category "Downloads" is in Cart items!'), 'notice' );
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

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