获取客户在 WooCommerce 中最后订单的产品

问题描述 投票:0回答:1

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

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

这是代码:

// 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>';
php wordpress woocommerce product orders
1个回答
3
投票

您可以使用

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>';
    }
}

相关:如何通过短代码在 WooCommerce 中显示最后订购的产品

© www.soinside.com 2019 - 2024. All rights reserved.