PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 9, 2022

[FIXED] How to display the last ordered product in WooCommerce via a shortcode

 May 09, 2022     orders, product, shortcode, woocommerce, wordpress     No comments   

Issue

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?


Solution

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]');


Answered By - 7uc1f3r
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing