wordpress 获取WooCommerce订单中每个项目的产品类别

wqsoz72f  于 5个月前  发布在  WordPress
关注(0)|答案(1)|浏览(54)

我可以检索订单项的几乎所有元数据,但我也想检索项的类别。
我的代码现在是这样的:

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

字符串
本以为这会起作用,但它不起作用:$product_category = $product->get_category();
我需要哪条线?

o4tp2gmn

o4tp2gmn1#

WC_Product方法get_category()不存在,我记得你可以为一个产品设置许多产品类别。
有多种方法可以在产品中设置产品类别:
1.您可以使用方法get_category_ids()来获取**产品类别Ids (术语Ids数组),如:

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
    }

字符串
1.或者要获取**产品类别名称 (术语名称数组),您可以使用wp_get_post_terms(),如下所示:

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

相关问题