如何获取订单商品 ID 以获取一些产品元数据?

新手上路,请多包涵

我正在尝试使用以下方法从 Woocommerce 的订单中提取项目元值:

 $data = wc_get_order_item_meta( $item, '_tmcartepo_data', true );

但是,我找不到将 order_item_id 作为第一个参数的方法(使用 get_items)

 global $woocommerce, $post, $wpdb;
$order = new WC_Order($post->ID);
$items = $order->get_items();

foreach ( $items as $item ) {
    $item_id = $item['order_item_id']; //???
    $data = wc_get_order_item_meta( $item_id, '_tmcartepo_data', true );
    $a = $data[0]['value'];
    $b = $data[1]['value'];
    echo $a;
    echo $b;
}

我的意思是这个订单 item_id (1 和 2)

数据库中的 Order_item_id - 图像

我该怎么做?

谢谢。

原文由 camelot 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 636
2 个回答

2018 年更新:

  • 用 2 种可能的情况澄清答案
  • 增加了对 woocommerce 3+ 的兼容性

所以可能有2种情况:

1)获取产品元数据(订单项元数据中未设置):

您需要在 foreach 循环中获取 WC_Order 的产品 ID 并获取该产品的一些元数据,您将使用 get_post_meta() 函数 (但不是 wc_get_order_item_meta() ) .

所以这是你的代码:

 global $post;
$order = wc_get_order( $post->ID );
$items = $order->get_items();

foreach ( $order->get_items() => $item ) {

    // Compatibility for woocommerce 3+
    $product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $item['product_id'] : $item->get_product_id();

    // Here you get your data
    $custom_field = get_post_meta( $product_id, '_tmcartepo_data', true);

    // To test data output (uncomment the line below)
    // print_r($custom_field);

    // If it is an array of values
    if( is_array( $custom_field ) ){
        echo implode( '<br>', $custom_field ); // one value displayed by line
    }
    // just one value (a string)
    else {
        echo $custom_field;
    }
}


2)获取订单商品元数据(自定义字段值):

 global $post;
$order = wc_get_order( $post->ID );
$items = $order->get_items();

foreach ( $order->get_items() as $item_id => $item ) {

    // Here you get your data
    $custom_field = wc_get_order_item_meta( $item_id, '_tmcartepo_data', true );

    // To test data output (uncomment the line below)
    // print_r($custom_field);

    // If it is an array of values
    if( is_array( $custom_field ) ){
        echo implode( '<br>', $custom_field ); // one value displayed by line
    }
    // just one value (a string)
    else {
        echo $custom_field;
    }
}


如果自定义字段数据是一个数组,您可以在 foreach 循环中访问数据:

 // Iterating in an array of keys/values
foreach( $custom_field as $key => $value ){
    echo '<p>key: '.$key.' | value: '.$value.'</p>';
}

所有代码都经过测试并且可以工作。

订单数据相关参考:

原文由 LoicTheAztec 发布,翻译遵循 CC BY-SA 3.0 许可协议

一种从数据库中获取订单商品的简单方法;

 /**
 * @param $order_id
 *
 * @return array|null|object
 */
function get_order_items( $order_id ) {
    global $wpdb, $table_prefix;

    $items     = $wpdb->get_results( "SELECT * FROM `{$table_prefix}woocommerce_order_items` WHERE `order_id` = {$order_id}" );
    $item_name = array();

    foreach ( $items as $item ) {
        $item_name[] = $item->order_item_name;
    }

    return $item_name;
}

原文由 Mostafa Soufi 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题