簡體   English   中英

獲取WooCommerce訂單中每個項目的產品類別

[英]Get product category for every item of a WooCommerce order

我幾乎可以檢索到訂單項的每個元數據,但我也想檢索這些項的類別。

我的代碼現在有這個:

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

我需要哪條線?

WC_Product方法get_category()不存在,我記得您可以為產品設置許多產品類別。

有多種方法可以獲取產品中設置的產品類別:

1)您可以使用方法get_catogory_ids()來獲取產品類別ID (術語ID的數組),例如:

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
}

2)或要獲取產品類別名稱 (術語名稱數組) ,可以使用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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM