[Solved] Get Woocommerce last order id from database using php


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

solved Get Woocommerce last order id from database using php