phpwordpresswoocommerceproductorders

Get products of the customer's last order in WooCommerce


I would like to obtain the data of the products of the last purchase or the most recent purchase of the client.

Currently I have this but the results of the array give me those of a random purchase, it does not even give me the data of a completed purchase. It gives me the details of a purchase that is on hold, I need a little help here.

Here is the code:

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

Solution

  • You can use wc_get_customer_last_order( $user_id ) to get info about customer’s last order.

    So you get:

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

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