Home > Net >  How to display the last ordered product in WooCommerce via a shortcode
How to display the last ordered product in WooCommerce via a shortcode

Time:12-29

I'm looking for a way to display the last ordered product on another page.

I think it would be possible to maybe create a shortcode in the functions that takes the order details and displays them wherever I add the shortcode.

Here is an example of what I mean.


But I can't seem to figure out how to get it to work. So far I got this information to work with:

add_shortcode( 'displaylast', 'last' );
function last(){
    $customer_id = get_current_user_id();
    $order = wc_get_customer_last_order( $customer_id );
    return $order->get_order();
}

[displaylast] is currently showing me noting. It does work when I change get_order() to get_billing_first_name().

That displays the order name. But I can't seem to get the item that was bought. Maybe there is a get_() that I'm not seeing?

CodePudding user response:

You are close, however you must obtain the last product from the order object.

So you get:

function last() {
    // 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 items
    $order_items = $last_order->get_items();
    
    // Latest WC_Order_Item_Product Object instance
    $last_item = end( $order_items );

    // Get product ID
    $product_id = $last_item->get_variation_id() > 0 ? $last_item->get_variation_id() : $last_item->get_product_id();
    
    // Pass product ID to products shortcode
    return do_shortcode("[product id='$product_id']");
} 
// Register shortcode
add_shortcode( 'display_last', 'last' ); 

SHORTCODE USAGE

In an existing page:

[display_last]

Or in PHP:

echo do_shortcode('[display_last]');
  • Related