Get product category for every item of a WooCommerce order

时间:2019-04-08 13:03:15

标签: php wordpress woocommerce orders taxonomy-terms

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?

1 个答案:

答案 0 :(得分:0)

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_catogory_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
}

2) 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);
}