使用 Woocommerce 2.6.8 ,我无法获得 文档 中描述的 Order Item Data 信息以及 此处的 SO 。
我想要的只是获取行项目价格和数量,这应该很简单:
$order = new WC_Order( $order_id );
$order_items = $order->get_items();
foreach ($order_items as $items_key => $items_value) {
echo $items_value['name']; //this works
echo $items_value['qty']; //this doesn't work
echo $items_value[item_meta][_qty][0]; //also doesn't work
echo $items_value['line_total']; //this doesn't work
}
仔细查看返回的内容
Array
(
[1] => Array
(
[name] => Sample Product 1
[type] => line_item
[item_meta] =>
[item_meta_array] => Array
(
[1] => stdClass Object
(
[key] => _qty
[value] => 1
)
[2] => stdClass Object
(
[key] => _tax_class
[value] =>
)
[3] => stdClass Object
(
[key] => _product_id
[value] => 8
)
[4] => stdClass Object
(
[key] => _variation_id
[value] => 0
)
[5] => stdClass Object
(
[key] => _line_subtotal
[value] => 50
)
[6] => stdClass Object
(
[key] => _line_total
[value] => 50
)
[7] => stdClass Object
(
[key] => _line_subtotal_tax
[value] => 0
)
[8] => stdClass Object
(
[key] => _line_tax
[value] => 0
)
[9] => stdClass Object
(
[key] => _line_tax_data
[value] => a:2:{s:5:"total";a:0:{}s:8:"subtotal";a:0:{}}
)
)
)
)
这都是使用记录在案的 Woocommerce 方法,为什么我需要的信息存储在这个 item_meta_array
中?
有谁知道我如何获得这些信息?
最好使用记录在案的方法,而不是通过 item_meta_array
循环的粗略破解,直到找到我正在寻找的密钥。
我觉得我必须在这里遗漏一些明显的东西。
原文由 robobobobo 发布,翻译遵循 CC BY-SA 4.0 许可协议
现在对于代码,您可以使用
WC_Order_Item_Product
(和WC_Product
)方法,例如:更新: 还有以下所有
WC_Abstract_Order
方法 允许使用各种有趣的选项获取订单项目数据,例如:感谢@Casper 的评论
此外
WC_Data
方法 可用于将订单项目数据作为不受保护的数组获取或从特定元键获取特定的嵌套或自定义元数据值:此代码经过测试并且可以工作。
// Getting the order object “\(order" \)order = wc_get_order( \(order_id ); // Getting the items in the order \)order_items = \(order->get_items(); // Iterating through each item in the order foreach (\)order_items as \(item_id => \)item) { // Get the product name \(product_name = \)item[‘name’]; // Get the item quantity \(item_quantity = \)order->get_item_meta(\(item_id, '_qty', true); // Get the item line total \)item_total = \(order->get_item_meta(\)item_id, ‘_line_total’, true);
}
”`
此代码经过测试并且功能齐全。
参考: 类 WC_Abstract_Order 方法