【问题标题】:Get product category for every item of a WooCommerce order获取 WooCommerce 订单的每个项目的产品类别
【发布时间】:2019-08-29 15:29:07
【问题描述】:

我几乎可以检索订单商品的所有元数据,但我也想检索商品的类别。

我的代码现在有这个:

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(),只有接近的方法是get_category_ids( string $context = 'view' )
  • 是显示类别还是只显示ID?

标签: php wordpress woocommerce orders taxonomy-terms


【解决方案1】:

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() like:

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

【讨论】:

    猜你喜欢
    • 2015-07-16
    • 2020-12-09
    • 1970-01-01
    • 2019-01-26
    • 2018-04-10
    • 2021-12-06
    • 1970-01-01
    • 2018-06-09
    • 2016-01-09
    相关资源
    最近更新 更多