使用 php 从数据库中获取 Woocommerce 最后一个订单 ID

Get Woocommerce last order id from database using php

在 Woocommerce 中,我尝试使用以下代码获取最后一个订单 ID:

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

但它不起作用,因为我得到的是零值。

目的是将最后一个订单ID加1,得到新的可用订单ID。

感谢任何帮助。

看来你想获取下一个可用的POST ID (Order Id),保存一下,例如,作为数据库中具有一些相关数据的新订单。

绝对不是的方法,您需要认为它与众不同...现在您可以使用其中一种方法以下3种方式:

  1. 使用 WordPress 专用函数 wp_insert_post() 即 returns post ID(订单 ID)。

  2. 使用 Woocommerce 专用函数 wc_create_order() 即 returns WC_Order 对象。

    然后从订单对象中,您可以使用 $order->get_id().

  3. 获取订单 ID
  4. 使用 WoocommerceWC_Order 对象实例和 save() 方法:

    // 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 - 获取 Woocommerce 中的最后一个订单 ID:

要在 woocommerce 中获取并显示最后一个订单 ID,请在这两行中使用 WC_Order_Query

<?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
?>

已测试并有效