在 WooCommerce 中从当前用户订单中获取订单 ID [英] Get the order id from the current user orders In WooCommerce
问题描述
情况是这样的.我有一个用作市场的 woocommerce 网站.我在上面卖游戏,有些买家会收到一个 Steam 密钥.为此,我正在研究一个关键属性系统,因此通过访问页面,关键将是用户的属性.
Here is the situation. I have a woocommerce site used as a marketplace. I'm selling games on it, for some the purchaser receive a steam key. For that I'm working on a key attribution system, so by going on a page, the key will be attributes to the user.
为此,我想检查当前用户下的所有订单(登录时和页面上)并检查他购买的游戏.
For that, I want to check all orders made by the current user (the on log-in and on the page) and check the game he has bought.
我在这里找到了一些非常有用的信息:如何获取 WooCommerce 订单详细信息
I find some very usefull information here: How to get WooCommerce order details
但是,我无法获得当前用户的所有订单.我首先想发出一个SQL请求,但我在数据库上没有找到订单和用户之间的链接.
However, I don't manage to get all orders the current user. I have first think to make a SQL request, but I don't find the link on the database between order and user.
你有线索吗?
推荐答案
更新 增加了与 WooCommerce 3+ 的兼容性(2018 年 1 月)
这是您获取所有客户订单并检查每个客户订单的每个项目所需的代码:
Here is the code that you will need to get all customer orders and to go through each items of each customer order:
## ==> Define HERE the statuses of that orders
$order_statuses = array('wc-on-hold', 'wc-processing', 'wc-completed');
## ==> Define HERE the customer ID
$customer_user_id = get_current_user_id(); // current user ID here for example
// Getting current customer orders
$customer_orders = wc_get_orders( array(
'meta_key' => '_customer_user',
'meta_value' => $customer_user_id,
'post_status' => $order_statuses,
'numberposts' => -1
) );
// Loop through each customer WC_Order objects
foreach($customer_orders as $order ){
// Order ID (added WooCommerce 3+ compatibility)
$order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;
// Iterating through current orders items
foreach($order->get_items() as $item_id => $item){
// The corresponding product ID (Added Compatibility with WC 3+)
$product_id = method_exists( $item, 'get_product_id' ) ? $item->get_product_id() : $item['product_id'];
// Order Item data (unprotected on Woocommerce 3)
if( method_exists( $item, 'get_data' ) ) {
$item_data = $item->get_data();
$subtotal = $item_data['subtotal'];
} else {
$subtotal = wc_get_order_item_meta( $item_id, '_line_subtotal', true );
}
// TEST: Some output
echo '<p>Subtotal: '.$subtotal.'</p><br>';
// Get a specific meta data
$item_color = method_exists( $item, 'get_meta' ) ? $item->get_meta('pa_color') : wc_get_order_item_meta( $item_id, 'pa_color', true );
// TEST: Some output
echo '<p>Color: '.$item_color.'</p><br>';
}
}
此代码已经过测试并有效
This code is tested and works
相关:
这篇关于在 WooCommerce 中从当前用户订单中获取订单 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!