首页 > 解决方案 > 使用 php 从数据库中获取 Woocommerce 的最后一个订单 ID

问题描述

在 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。

任何帮助表示赞赏。

标签: phpdatabasewordpresswoocommerceorders

解决方案


似乎您想获取下一个可用的POST ID (Order Id),以将其保存为数据库中的新订单以及一些相关数据。

绝对不是这样做的方法,您需要考虑不同...现在您可以使用以下 3 种方法之一:

  1. 使用返回帖子 ID(订单 ID)的 WordPress专用函数wp_insert_post()

  2. wc_create_order()使用返回WC_OrderObject的 Woocommerce专用函数。

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

  3. 使用 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();
    

加法- 获取 Woocommerce 中的最后一个订单 ID:

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

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

测试和工作


推荐阅读