Search code examples
wordpresswoocommerceshortcodeorders

How to grab the order status of the last order in WooCommerce via a shortcode


I'm trying to give our customers a better insight in their order status without going to their account. My plan is to print the info on the home page once someone has ordered.

Sample of how I want it to look

I'm struggling to get the order status to display elsewhere.

Here is the current code I've whipped up based on a code used to grab the product of the last order.

function woostatus() {
    // Not available
    $na = __( 'N/A', 'woocommerce' );
    
    // For logged in users only
    if ( ! is_user_logged_in() ) return $na;

    // The current user ID
    $user_id = get_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();
    
    // When empty
    if ( empty ( $last_order ) ) return $na;
     
     // Get order date
    $order_items = $last_order->get_status();
    
    // Latest WC_Order_Item_Product Object instance
    $last_item = end( $order_items );

    // Pass product ID to products shortcode
    return $order_items;
}  
// Register shortcode 
add_shortcode( 'display_woostatus', 'woostatus' );

Solution

  • $order_items = $last_order->get_status() will return a string and is therefore not an array. So using end( $order_items ) is a superfluous step.

    Use instead:

    function woostatus() {
        // Not available
        $na = __( 'N/A', 'woocommerce' );
        
        // For logged in users only
        if ( ! is_user_logged_in() ) return $na;
    
        // The current user ID
        $user_id = get_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();
        
        // When empty
        if ( empty ( $last_order ) ) return $na;
        
        // Get order status
        $order_status = $last_order->get_status();
        
        // Return
        return $order_status;
    } 
    // Register shortcode
    add_shortcode( 'display_woostatus', 'woostatus' ); 
    

    SHORTCODE USAGE

    In an existing page:

    [display_woostatus]
    

    Or in PHP:

    echo do_shortcode('[display_woostatus]');