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.