Search code examples
phphtmlwordpresswoocommerceorders

Display a custom text when a registered customer has not yet purchased in WooCommerce


In WooCommerce I have the following code that displays orders items names and order status from last customer order (registered customer):

 <?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


<div class="row last-order">
    <div class="col-md-7">
        <ul>
        <?php foreach ( $last_order->get_items() as $item ) : ?>
            <li><?php echo $item->get_name(); ?></li>
        <?php endforeach; ?>
      </ul>
    </div>
    <div class="col-md-4 order-status-box">
      <h6 class="status"><?php echo esc_html( wc_get_order_status_name( $order_status ) ); ?></h6>
      <i class="fas fa-chevron-down icon"></i>
    </div>
</div>

<?php endif; ?>

However, if the customer does not have any order, I would like it to display something like "Have not purchased yet". I didn't find yet the way to do it.

How and where to add a condition to display a custom text, when there is no last order for a registered customer?


Solution

  • Try the following, to display a custom text when a logged in customer has not purchased yet:

    <?php
    // For logged in users only
    if ( is_user_logged_in() ) :
    
    // Get the current WC_Customer instance Object
    $customer = new WC_Customer( get_current_user_id() );
    
    // Get the last WC_Order Object instance from current customer
    $last_order = $customer->get_last_order();
    
    ?>
    <div class="row last-order">
    <?php
    
    if( is_a($last_order, 'WC_Order') ) :
    ?>
    <div class="col-md-7">
    <div class="order_number">#<?php echo $last_order->get_order_number(); ?></div>
        <ul>
        <?php foreach ( $last_order->get_items() as $item ) : ?>
            <li><?php echo $item->get_name(); ?></li>
        <?php endforeach; ?>
        </ul>
    </div>
    <div class="col-md-4 order-status-box">
        <h6 class="status"><?php echo esc_html( wc_get_order_status_name( $last_order->get_status() ) ); ?></h6>
        <i class="fas fa-chevron-down icon"></i>
    </div>
    <?php else : ?>
    <p><?php _e("You have not made a purchased yet.", "woocommerce"); ?></p>
    <?php endif; ?>
    </div>
    <?php endif; ?>
    

    Tested and works.