Search code examples
phpwordpresswoocommerceorderstaxonomy-terms

How to get product category ids from order items in WooCommerce


I am working on to get the categories of each product which is ordered using below code.

function get_order_detail($order_id){
    $order = wc_get_order( $order_id );


    foreach ($order->get_items() as $item_key => $item ){
        $product = $item->get_product();
        $categorieID = $product->category_ids[0];
        $categorie_title = get_the_category_by_ID($categorieID);
    }
}

But the products which were having variants like size, colour in their variations, they are returning the value of $categorieID as NULL.


Solution

  • Use the following instead to get the product category term names for each order item:

    function get_order_detail( $order_id ) {
        $order = wc_get_order( $order_id );
    
        foreach ( $order->get_items() as $item_id => $item ) { 
            // Get the product category(ies) term(s) name(s) - (array)
            $term_names = wp_get_post_terms( $item->get_product_id(), 'product_cat', array('fields' => 'names') );
            // Set them as a coma separated string
            $categories_string = implode(',', $term_names);
    
        }
    }
    

    or you can get the product category Ids using the following:

    function get_order_detail( $order_id ) {
        $order = wc_get_order( $order_id );
    
        foreach ( $order->get_items() as $item_id => $item ) { 
            // Get the product category(ies) term(s) Id(s) - (array)
            $term_ids = wp_get_post_terms( $item->get_product_id(), 'product_cat', array('fields' => 'ids') );
        }
    }
    

    This will work for all product types even variations of a variable product.