Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get product category for every item of a WooCommerce order

I can retrieve almost every metadata of the order items but I want to retrieve the category of the items too.

My code now has this:

foreach ($order->get_items() as $item_key => $item_values) {

    ## Using WC_Order_Item methods ##

    // Item ID is directly accessible from the $item_key in the foreach loop or
    $item_id = $item_values->get_id();

    ## Using WC_Order_Item_Product methods ##

    $item_name = $item_values->get_name(); // Name of the product
    $item_type = $item_values->get_type(); // Type of the order item ("line_item")

    $product_id = $item_values->get_product_id(); // the Product id
    $product = $item_values->get_product(); // the WC_Product object

    ## Access Order Items data properties (in an array of values) ##
    $item_data = $item_values->get_data();

    $product_name = $item_data['name'];
    $item_totaal = $item_data['subtotal']; 

    // Get data from The WC_product object using methods (examples)
    $product_type   = $product->get_type();
    $product_price  = $product->get_price();
}

Thought this would work but it doesn't: $product_category = $product->get_category();

What line do I need?

like image 639
PelHout Avatar asked Dec 29 '25 09:12

PelHout


1 Answers

The WC_Product method get_category() doesn't exist and I remember you that you can have many product categories set for a product.

There is multiple ways to get the product categories set in a product:

  1. You can use the method get_category_ids() to get the product categories Ids (an array of terms Ids) like:
    foreach ($order->get_items() as $item ) {
        $product = $item->get_product(); // the WC_Product Object

        $product_category_ids  = $product->get_category_ids(); // An array of terms Ids
    }
  1. Or to get the product category names (an array of term names) you can use wp_get_post_terms() like:
    foreach ($order->get_items() as $item ) {
        $term_names = wp_get_post_terms( $item->get_product_id(), 'product_cat', ['fields' => 'names'] );
    
        // Output as a coma separated string
        echo implode(', ', $term_names);
    }
like image 127
LoicTheAztec Avatar answered Dec 30 '25 23:12

LoicTheAztec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!