【问题标题】:Get Woocommerce last order id from database using php使用 php 从数据库中获取 Woocommerce 的最后一个订单 ID
【发布时间】:2019-08-18 15:16:07
【问题描述】:

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

感谢任何帮助。

【问题讨论】:

标签: php database wordpress woocommerce orders


【解决方案1】:

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

这绝对不是这样做的方式,您需要认为它不同...现在您可以使用以下 3 种方式之一:

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

  2. 使用 Woocommerce 专用函数 wc_create_order() 返回 WC_Order 对象。

    然后从订单对象中,您可以使用$order-&gt;get_id()获取订单ID。

  3. 使用 Woocommerce 空的 WC_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:

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

经过测试并且可以工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-27
    • 2019-06-14
    • 2021-07-19
    • 1970-01-01
    • 2019-03-21
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    相关资源
    最近更新 更多