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

Get products of the customer's last order in WooCommerce

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

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

代码如下:

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

相关: