【问题标题】:How to get product category ids from order items in WooCommerce如何从 WooCommerce 中的订单项中获取产品类别 ID
【发布时间】:2020-12-09 21:41:12
【问题描述】:
我正在努力获取使用以下代码订购的每个产品的类别。
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。
【问题讨论】:
标签:
php
wordpress
woocommerce
orders
taxonomy-terms
【解决方案1】:
使用以下命令获取每个订单项目的产品类别术语名称:
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') );
}
}
这适用于所有产品类型,甚至是可变产品的变体。