questions

Get product categories ids from order items in WooCommerce

Rate this post

I have a couple of code snippets to get product categories, they are working but they all miss out the category for variable products.

Could anyone point me in the right direction?

$items = $order->get_items();
$categories = array();
foreach($items as $item) {
    $product = $item->get_product();
    $product_categories = $product->get_category_ids();
    //...
}

This snippet has the same issue. (It is using a hook from an invoice plugin but I don’t think that is relevant)

add_action( 'wpo_wcpdf_after_item_meta', 'wpo_wcpdf_show_product_categories', 10, 3 );
function wpo_wcpdf_show_product_categories ($template_type, $item, $order) {
    wc_get_product_category_list( $item['product']->get_id() )
    //...
}

Products will only ever have one category if that matters.

I tried this as suggested somewhere but still returns false?

$the_product = wc_get_product( $item['product']->get_id() );
$variable_categories = wc_get_product_category_list( $the_product->get_id() );

Cheers!

 

✔️Solution:

To get product categories ids from order items, use the following instead:

$category_ids = array();

foreach($order->get_items() as $item) {
    $product = wc_get_product( $item->get_product_id() );

    $categories = array_merge( $category_ids, $product->get_category_ids() );
    //...
}

So in your hooked function:

add_action( 'wpo_wcpdf_after_item_meta', 'wpo_wcpdf_show_product_categories', 10, 3 );
function wpo_wcpdf_show_product_categories ( $template_type, $item, $order ) {
    wc_get_product_category_list( $item->product_get_id() )
    //...
}

This will work.

Leave a Reply

Your email address will not be published.

Back to top button