gpt4 book ai didi

php - 在 WooCommerce 中获取客户上次订单的产品

转载 作者:行者123 更新时间:2023-12-05 03:27:25 24 4
gpt4 key购买 nike

我想获取客户上次购买或最近一次购买的商品数据。

目前我有这个,但是数组的结果给我随机购买的结果,它甚至没有给我完成购买的数据。它为我提供了暂停购买的详细信息,我在这里需要一点帮助。

代码如下:

// Get the current user Object
$current_user = wp_get_current_user();

// Check if the user is valid
if (0 == $current_user->ID) return;

//Create $args array
$args = array(
'numberposts' => 1,
'meta_key' => '_customer_user',
'meta_value' => $current_user->ID,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => wc_get_order_types(),
'post_status' => array_keys(wc_get_is_paid_statuses()),
);

// Pass the $args to get_posts() function
$customer_orders = get_posts($args);

// loop through the orders and return the IDs
if (!$customer_orders) return;
$product_ids = array();
foreach ($customer_orders as $customer_order) {
$order = wc_get_order($customer_order->ID);
$items = $order->get_items();
foreach ($items as $item) {
$product_id = $item->get_product_id();
$product_ids[] = $product_id;
}
}
echo '<pre>';
var_dump($product_ids);
echo '</pre>';

最佳答案

您可以使用 wc_get_customer_last_order( $user_id )获取有关客户上次订单的信息。

所以你得到:

// For logged in users only
if ( is_user_logged_in() ) {

// The current user ID
$user_id = get_current_user_id();

// Get the last WC_Order Object instance from current customer
$last_order = wc_get_customer_last_order( $user_id );

// NOT empty
if ( ! empty( $last_order ) ) {
// Initalize
$product_ids = array();

// Loop
foreach ( $last_order->get_items() as $item ) {
// Get product ID
$product_id = $item->get_product_id();
$product_ids[] = $product_id;
}

echo '<pre>';
var_dump( $product_ids );
echo '</pre>';
}
}

相关:How to display the last ordered product in WooCommerce via a shortcode

关于php - 在 WooCommerce 中获取客户上次订单的产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71501576/

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