如果用户登录 Woocommerce,如何获取最新的订单 ID? [英] How to get latest order ID if user logged in Woocommerce?
本文介绍了如果用户登录 Woocommerce,如何获取最新的订单 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试获取用户购买的最新订单 ID,以在不同的页面模板中显示产品的一些自定义字段.
I am trying to get the latest order id purchased by a user to display some of the custom fields of a product in the different page template.
if ( is_user_logged_in() ){
$current_user_id= get_current_user_id();
$latest_order_id = get_last_order_id(); // Last order ID
$order = wc_get_order( $latest_order_id ); // Get an instance of the WC_Order object
$order_details = $order->get_data(); // Get the order data in an array
$order_status = esc_html( wc_get_order_status_name( $order->get_status() ) );
$order_items = $order_details['line_items'];
}else{
'Not Purchased'
}
推荐答案
使用这个:
if ( is_user_logged_in() ){
$order_statuses = array('wc-on-hold', 'wc-processing', 'wc-completed');
$customer_user_id = get_current_user_id();
$customer_orders = get_posts(array(
'numberposts' => 1,
'meta_key' => '_customer_user',
'meta_value' => $customer_user_id,
'post_type' => 'shop_order',
'post_status' => array('wc-pending', 'wc-processing', 'wc-completed') //array_keys(wc_get_order_statuses()),
));
if ( !empty( $customer_orders ) ) {
echo $latest_order_id = $customer_orders[0]->ID;
}
}
或
function func_get_last_order_id(){
if ( is_user_logged_in() ){
$customer_user_id = get_current_user_id();
$last_order = wc_get_customer_last_order( $customer_user_id );
if ( !empty( $last_order ) ) {
$order_id = $last_order->get_id();
echo $order_id;
}
}
}
add_action('woocommerce_after_register_post_type', 'func_get_last_order_id');
这篇关于如果用户登录 Woocommerce,如何获取最新的订单 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文