【问题标题】:How can I get the latest order id in Woocommerce如何在 Woocommerce 中获取最新的订单 ID
【发布时间】:2018-03-23 04:09:56
【问题描述】:

在 Woocommerce 中,我正在尝试获取最新的订单 ID。我试过这个:

global $post;
$order_id = $post->ID;

$order = new WC_Order($order_id);
$order_details = $order->get_data();

但它没有用。

如何在woocommerce中获取最新的订单ID?

【问题讨论】:

    标签: php sql wordpress woocommerce orders


    【解决方案1】:

    这是一个自定义函数,它将返回最后一个订单 ID:

    function get_last_order_id(){
        global $wpdb;
        $statuses = array_keys(wc_get_order_statuses());
        $statuses = implode( "','", $statuses );
    
        // Getting last Order ID (max value)
        $results = $wpdb->get_col( "
            SELECT MAX(ID) FROM {$wpdb->prefix}posts
            WHERE post_type LIKE 'shop_order'
            AND post_status IN ('$statuses')
        " );
        return reset($results);
    }
    

    代码进入您的活动子主题(活动主题或任何插件文件)的 function.php 文件中。


    用法 (示例)

    $latest_order_id = get_last_order_id(); // Last order ID
    $order = wc_get_order( $latest_order_id ); // Get an instance of the WC_Order oject
    $order_details = $order->get_data(); // Get the order data in an array
    
    // Raw output test
    echo '<pre>'; print_r( $order_details ); echo '</pre>';
    

    经过测试和工作。

    【讨论】:

    • 你好 Loic 。结果是针对客户还是会考虑所有订单?
    • @LatheeshVMVilla 不,对于客户,我认为 SQL 查询需要有所不同……但您可以使用 wc_get_orders 来做到这一点
    猜你喜欢
    • 2017-10-27
    • 2014-03-05
    • 2019-09-08
    • 2020-05-08
    • 2021-07-14
    • 2019-06-14
    • 2015-11-27
    • 1970-01-01
    • 2017-07-08
    相关资源
    最近更新 更多