php - 如何在 Woocommerce 中获取客户的最后一个订单
问题描述
我正在使用“如何在 Woocommerce 中获取最新的订单 ID ”答案代码,该代码使用自定义函数返回最后一个订单get_last_order_id()
。
这是我获取订单商品的代码尝试:
<?php
$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'];
?>
然后我在这段代码中使用它:
<div class="row last-order">
<div class="col-md-7">
<ul>
<?php
foreach ($order_items as $product_name) { ?>
<li><?php echo $product_name['name']; ?></li>
<?php
}
?>
</ul>
</div>
<div class="col-md-4 order-status-box">
<h6 class="status"><?php echo $order_status; ?></h6>
<i class="fas fa-chevron-down icon"></i>
</div>
</div>
我想得到当前客户的最后一个订单。如何更改自定义功能get_last_order_id()
以获取当前客户的最后一个订单?
除了当前用户的最新订单外,我还想收到我购物车中的内容。
解决方案
更新:替换
WC()->customer
为以new WC_Customer( get_current_user_id() );
获得更好的兼容性。
Class WC_Customer
Class 包括get_last_order()
获取客户最后一个订单的方法(因此您不再需要此答案线程get_last_order_id()
中的自定义函数)。
所以你的代码将是:
<?php
// For logged in users only
if ( is_user_logged_in() ) :
$user_id = get_current_user_id(); // The current user ID
// Get the WC_Customer instance Object for the current user
$customer = new WC_Customer( $user_id );
// Get the last WC_Order Object instance from current customer
$last_order = $customer->get_last_order();
$order_id = $last_order->get_id(); // Get the order id
$order_data = $last_order->get_data(); // Get the order unprotected data in an array
$order_status = $last_order->get_status(); // Get the order status
?>
<div class="row last-order">
<div class="col-md-7">
<ul>
<?php foreach ( $last_order->get_items() as $item ) : ?>
<li><?php echo $item->get_name(); ?></li>
<?php endforeach; ?>
</ul>
</div>
<div class="col-md-4 order-status-box">
<h6 class="status"><?php echo esc_html( wc_get_order_status_name( $order_status ) ); ?></h6>
<i class="fas fa-chevron-down icon"></i>
</div>
</div>
<?php endif; ?>
测试和工作。
注意:现在要“接收购物车中的内容以及当前用户的最新订单”,您将不得不提出一个更详细的新问题,请同时提出一个问题。
有关的:
推荐阅读
- audio - 使用 FFMPEG 将 MP3 与 MP4 合并。最后出乎意料的沉默
- android - 我想在 Android 中开发一个基于问答游戏的应用程序
- python - 循环遍历 DataFrames 的名称以删除 dup 和 group by 并在 Python 中创建新的 DataFrames
- google-apps-script - 根据特定单元格范围内的值从特定范围内删除谷歌电子表格中的行
- reactjs - 反应 - 为什么我的过滤方法不起作用
- android - Flutter 以 Stream 形式接收共享意图文本
- excel - 解锁和锁定受保护的工作表
- python - 如何在#document标签内的python中获取html?
- firebase - 在 Firebase 云功能中创建用户而不是在本地创建用户是否有优势?
- python - 如何在 Plotly Dash 中设置数据标签