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

问题描述

我正在努力获取使用以下代码订购的每种产品的类别。

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(),array('fields' => 'ids') );
    }
}

这将适用于所有产品类型,甚至是可变产品的变体。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...