How can I get the latest order id in Woocommerce

ε祈祈猫儿з 提交于 2019-12-12 17:24:43

问题


In Woocommerce I am trying to get the latest order ID. I have tried this:

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

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

But it didn't work.

How to get the latest order ID in woocommerce?


回答1:


Here is a custom function that will return the last order 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);
}

Code goes in function.php file of your active child theme (active theme or in any plugin file).


USAGE (Example):

$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>';

Tested and work.



来源:https://stackoverflow.com/questions/46688978/how-can-i-get-the-latest-order-id-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!