Php 如何从WooCommerce中的订单项获取产品类别ID

Php 如何从WooCommerce中的订单项获取产品类别ID,php,wordpress,woocommerce,orders,taxonomy-terms,Php,Wordpress,Woocommerce,Orders,Taxonomy Terms,我正在努力获得每一个产品的类别,这是使用下面的代码订购 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-&g

我正在努力获得每一个产品的类别,这是使用下面的代码订购

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

但是这些产品在尺寸、颜色等方面存在差异,
他们将$categorieID的值返回为NULL。

使用以下方法获取每个订单项的产品类别术语名称:

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

    }
}
或者,您可以使用以下方法获取产品类别ID:

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') );
    }
}
这将适用于所有产品类型,甚至是可变产品的变体