gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:10:38 32 4
gpt4 key购买 nike

我正在尝试使用以下方法从 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 in database - Image

我该怎么穿?

谢谢。

最佳答案

2018 Update:

  • Clarifying the answer with 2 possible cases
  • Added compatibility for woocommerce 3+

所以可以有2种情况:

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

您需要在 WC_Order 的 foreach 循环中获取产品 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>';
}

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

订单相关数据引用:

关于php - 如何获取订单商品 ID 以获取一些产品元数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39390838/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com