Checking cart items for a product category in Wooc

2019-05-23 07:57发布

In woocommerce, I'm trying to check in cart items for a particular product category using:

add_action('woocommerce_before_cart', 'fs_check_category_in_cart');
function fs_check_category_in_cart() {
    // Set $cat_in_cart to false
    $cat_in_cart = false;
    // Loop through all products in the Cart        
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $product = $cart_item['data'];
        echo '<pre>',print_r($product),'</pre>';
        // If Cart has category "download", set $cat_in_cart to true
        if ( has_term( 'downloads', 'product_cat', $product->get_id() ) ) {
            $cat_in_cart = true;
            break;
        }
    }
    // Do something if category "download" is in the Cart      
    if ( $cat_in_cart ) {

        // For example, print a notice
        wc_print_notice( 'Category Downloads is in the Cart!', 'notice' );
        // Or maybe run your own function...
        // ..........
    }
}

Ive been unable to achieve it. On further inspection when I print_r( $product ) the end of the array look like:

            [current_class_name:WC_Data_Store:private] => WC_Product_Data_Store_CPT
            [object_type:WC_Data_Store:private] => product-simple
    )

    [meta_data:protected] => 
)
1

This 1 at the end of the array is attaching its self to any variable I try and reference. So I get

downloads1 

If anyone knows where this number maybe coming from its been stressing me out!

Just for the record also doing print_r( $woocommerce ) has the 1 at the end of the array.

Any help is appreciated.

1条回答
Juvenile、少年°
2楼-- · 2019-05-23 08:49

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.

查看更多
登录 后发表回答