-6

In Woocommerce, I am trying to get the last order id using the following code:

<?php $order = new WC_Order($post->ID);echo $order->id;//to escape # from order id $order_id = trim(str_replace('#', '', $order->get_order_number())); ?>

But it doesn't work as I am getting a zero value.

The purpose is to add 1 to this last order ID, to get the new usable order ID.

Any help is appreciated.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • 5
    I voted down because SO is not a free code service, also this question is too vague to give a proper answer. –  Mar 27 '19 at 22:51
  • 2
    Not to mention arbitrarily adding `1` to a primary key is generally a bad Idea. Order Id being the same thing as `posts.ID` – ArtisticPhoenix Mar 27 '19 at 22:52
  • 6
    Welcome to StackOverflow! We are **NOT** a free coding service, and your 'question' doesn't show any attempt whatsoever. Please review [**this letter**](https://softwareengineering.meta.stackexchange.com/questions/6166) and update your question to at least [**showcase an attempt**](http://meta.stackoverflow.com/questions/261592) in a [**minimal, complete, and verifiable example**](http://stackoverflow.com/help/mcve). For further information, please see [**how to ask good questions**](http://stackoverflow.com/help/how-to-ask), and take the [**tour of the site**](http://stackoverflow.com/tour). – Obsidian Age Mar 27 '19 at 22:53
  • https://stackoverflow.com/questions/39401393/how-to-get-woocommerce-order-details –  Mar 27 '19 at 23:43

1 Answers1

1

It seems that you would like to get the next usable POST ID (Order Id), to save it, for example, as new Order in database with some related data.

This is absolutely not the way to do it and you need to think it different... Now you can use one of the 3 following ways:

  1. Using the WordPress dedicated function wp_insert_post() that returns the post ID (Order ID).

  2. Using the Woocommerce dedicated function wc_create_order() that returns the WC_Order Object.

    Then from the the order object, you can get the order ID using $order->get_id().

  3. Using the Woocommerce empty WC_Order object instance and the save() method:

    // Get an empty instance of the `WC_Order` Object
    $order = new WC_Order();
    
    // Save the order to the database
    $order->save();
    
    // Get the Order ID
    $order_id = $order->get_id();
    

Addition - Get the last Order ID in Woocommerce:

To get and display the last order ID in woocommerce use a WC_Order_Query in this two simple line:

<?php
    $last_order_id = wc_get_orders(array('limit' => 1, 'return' => 'ids')); // Get last Order ID (array)
    echo (string) reset($last_order_id); // Displaying last order ID
?>

Tested and works

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399