I’m trying to build an accessible and user-friendly dashboard. So I wanted to offer the user the details of the last purchase made. Doing some research I found this post: How to get the last order of a customer in Woocommerce
I have implemented the recommended solution and everything seems to be working fine. The only problem is that if the user didn’t place any order then the page view is bugged.
I have implemented the code in the following way, could someone point me where I’m wrong ?
//Start Woocommerce Add Info Order on Dashboard
<?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
$currency = $last_order->get_currency(); //Get Currency
?>
<?php foreach ( $last_order->get_items() as $item ) : ?>
<div class="last_order_items"><?php echo $item->get_name(); ?></div>
<div class="last_order_items"><?php echo $order_total = $order_data['total']; ?>€</div>
<div class="last_order_items"><?php echo $order_date_created = $order_data['date_created']->date('Y-m-d H:i:s'); ?></div>
<div class="last_order_items"><?php echo esc_html( wc_get_order_status_name( $order_status ) ); ?></div>
<?php endforeach; ?>
<?php endif; ?>
it works fine for me as the admin and I have some trial purchases, but not for users who have not made any purchases.
2
Answers
The solution posted by @jtowell works perfectly, thanks again. However, before this question was answered I was looking for a solution and I found this: Display a custom text when a registered customer has not yet purchased in WooCommerce
After that, I implemented my question code in the following way, this solution also worked:
As you mention this wont work correctly if a user has no orders yet. The get_last_order() returns false if this is the case. So you would need to check if get_last_order is false or not an object, and if so display some alternate html eg
I haven’t tested, but I am confident this should work