如果您有自定義訂單狀態,然後又發現用 get_posts function 怎麼樣都抓不到想要的訂單列表的話,這段code 可能就對你有用拉!很奇怪的,我用以下這段 code 怎麼都撈不出訂單。
$post_status_list = array_merge(array_keys( Ecpay_get_order_statuses() ), array_keys( wc_get_order_statuses() ));
$customer_orders = get_posts( apply_filters( 'woocommerce_my_account_my_orders_query', array(
'numberposts' => $order_count,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => wc_get_order_types( 'view-orders' ),
'post_status' => $post_status_list
) ) );
其中 Ecpay_get_order_statuses 是我參考 wc_get_order_statuses 幫 ecpay 定義的訂單狀態。內容如下,
function Ecpay_get_order_statuses(){
$order_statuses = array(
'wc-ecpay' => _x( '訂單已成立出貨中', 'Order status', 'woocommerce' ),
'wc-ecpay-send' => _x( '賣家已到門市寄件', 'Order status', 'woocommerce' ),
'wc-ecpay-receive' => _x( '商品已送達您指定的門市', 'Order status', 'woocommerce' ),
'wc-ecpay-finish' => _x( '消費者成功取件', 'Order status', 'woocommerce' ),
'wc-ecpay-fail' => _x( '消費者七天未取件', 'Order status', 'woocommerce' ),
);
return $order_statuses;
}
後來只好直接透過 wpdb ,直接進行 db 操作,來解決這個弔詭的問題了。
$post_status_list = array_merge(array_keys( Ecpay_get_order_statuses() ), array_keys( wc_get_order_statuses() ));
global $wpdb;
$post_status = implode("','", $post_status_list);
$user_id = get_current_user_id();
$customer_orders = $wpdb->get_results( "SELECT p.* FROM $wpdb->postmeta pm, $wpdb->posts p
where p.post_type = 'shop_order'
and post_status IN ('{$post_status}')
and pm.meta_key = '_customer_user'
and pm.meta_value = {$user_id}
and pm.post_id = p.ID
order by post_date desc
");