2017-10-11 74 views
1

我如何獲得最新的訂單ID?我如何獲得Woocommerce的最新訂單ID

這就是我現在所擁有的,但id(426)必須是動態的最新訂單ID。

我已經試過這樣:

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

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

但沒有奏效。

有人可以幫助我嗎?

回答

2

這裏是一個自定義函數將返回最後一個順序編號:

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文件(活動的主題或任何插件文件)。


USAGE(實施例)

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

測試和工作。

+0

感謝您的快速回答,它按預期工作。 –

相關問題