0

I am trying to get the latest order id purchased by a user to display some of the custom fields of a product in the different page template.

if ( is_user_logged_in() ){
        $current_user_id= get_current_user_id();
            $latest_order_id = get_last_order_id(); // Last order ID
            $order = wc_get_order( $latest_order_id ); // Get an instance of the WC_Order object
            $order_details = $order->get_data(); // Get the order data in an array
            $order_status = esc_html( wc_get_order_status_name( $order->get_status() ) );
            $order_items = $order_details['line_items'];
        }else{
            'Not Purchased'
        }
Praveen
  • 985
  • 8
  • 31

1 Answers1

1

Use this:

if ( is_user_logged_in() ){
    $order_statuses = array('wc-on-hold', 'wc-processing', 'wc-completed');
    $customer_user_id = get_current_user_id(); 

    $customer_orders = get_posts(array(
         'numberposts' => 1,
         'meta_key'    => '_customer_user',
         'meta_value'  => $customer_user_id,
         'post_type'   => 'shop_order',
         'post_status' => array('wc-pending', 'wc-processing', 'wc-completed') //array_keys(wc_get_order_statuses()),
    ));

    if ( !empty( $customer_orders ) ) {
        echo $latest_order_id = $customer_orders[0]->ID;
    }
}

Or

function func_get_last_order_id(){
    if ( is_user_logged_in() ){
        $customer_user_id = get_current_user_id(); 
        $last_order = wc_get_customer_last_order( $customer_user_id );
        if ( !empty( $last_order ) ) {
            $order_id = $last_order->get_id();
            echo $order_id;
        }
    }
}

add_action('woocommerce_after_register_post_type', 'func_get_last_order_id');
sumon cse-sust
  • 434
  • 4
  • 8