How to get the last order of a customer in Woocommerce

前端 未结 1 1723
终归单人心
终归单人心 2020-12-12 06:49

I am using \"How can I get the latest order id in Woocommerce\" answer code that returns last order with a custom function get_last_order_id().

<
相关标签:
1条回答
  • 2020-12-12 07:28

    Updated: replaced WC()->customer by new WC_Customer( get_current_user_id() ); for better compatibility.

    The Class WC_Customer Class include the get_last_order() method to get the last order for a customer (so you don't need anymore the custom function get_last_order_id() from this answer thread).

    So your code will be:

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

    Tested and works.

    Note: Now to "receive the contents of the cart in addition to the latest order from the current user", you will have to ask a new question with more details, one question at the time please.

    Related:

    • How to get WooCommerce order details
    • Get Order items and WC_Order_Item_Product in WooCommerce 3
    • How to get Customer details from Order in WooCommerce?
    0 讨论(0)
提交回复
热议问题