1

I want to get the categories of each product in the cart, then I have this code:

<?php
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) :
    $_product = $cart_item['data'];
    $array_cat[] = $_product->get_category_ids();
endforeach;
?>

This code works fine with simple product but with variable product it show empty.

I have tried this:

<?php
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) :
    $_product = $cart_item['data'];
    $array_cat1 = $_product->get_category_ids();
    $array_cat2 = wc_get_product_terms( $_product->get_id(),'product_cat' );
    $array_cat3 = wp_get_post_terms( $_product->get_id(),'product_cat' );
    $array_cat4 = get_the_terms( $_product->get_id(), 'product_cat' );
    $array_cat5 = get_the_term_list($_product->get_id(), 'product_cat');
endforeach;
?>

but in all these cases, it show empty.

Please could you help with it?

Regards

1

Ok, I resolved it.

In a variable product $_product->get_id() is not of ID the product else is the ID only of these variation at cart.

Then, in these loop can found the id of product in the variable $cart_item['product_id']

We can use it:

$the_product = wc_get_product( $cart_item['product_id'] );
$array_cat = $the_product->get_category_ids();

Regards

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.