Woocommerce wp_query 通过 ID 获取订单

Woocommerce wp_query get order by ID

我正在尝试生成订单数据的简单输出。第一步是 WP_QUery(可能)所以我写了这段代码;

$args = array (

    'post_type'  =>'shop_order',
    'posts_per_page' => -1,
    'post_status' => 'any',
    //'p' => $post_id,

);    

$order_query = new WP_Query( $args );

while ( $order_query->have_posts() ) :
  $order_query->the_post(); 

  echo the_ID();
  echo ' : '; 
  the_title();
  echo '<br/><br/>';

endwhile;

它要求产品列出所有订单,如果我设置 'p' => $post_id 其中 $post_id 是一个有效的 post ID,查询 returns 什么都没有。

蜂群思维,知道为什么吗?

或者有一种 Woocommerce 方法可以生成具有类似布局的普通页面;

Order ID: 836
Order Status: ....

我认为 WP_Query 是显而易见的方法,但看起来获取 woocommerce 订单数据并不简单。

更新 2

获取一份订单的订单数据,不需要WP_query。可以直接使用:

$order = wc_get_order( $order_id );
$order->id; // order ID
$order->post_title; // order Title
$order->post_status; // order Status
// getting order items
foreach($order->get_items() as $item_id => $item_values){
    // Getting the product ID
    $product_id = $item_values['product_id'];
    // .../...
}

更新 1

您应该试试这个,因为使用 array_keys( wc_get_order_statuses() 您将获得所有订单状态,使用 'numberposts' => -1,所有现有订单。

这是另一种方法(没有 WP_query 或者您可以在 WP_query 数组中使用这些参数):

$customer_orders = get_posts( array( 
    'numberposts'    => -1,
    'post_type' => 'shop_order',
    'post_status'    => array_keys( wc_get_order_statuses() ) 
) );

// Going through each current customer orders
foreach ( $customer_orders as $customer_order ) {

    // Getting Order ID, title and status
    $order_id = $customer_order->ID;
    $order_title = $customer_order->post_title;
    $order_status = $customer_order->post_status;

    // Displaying Order ID, title and status
    echo '<p>Order ID : ' . $order_id . '<br>';
    echo 'Order title: ' . $order_title . '<br>';
    echo 'Order status: ' . $order_status . '<br>';

    // Getting an instance of the order object
    $order = wc_get_order( $order_id );

    // Going through each current customer order items
    foreach($order->get_items() as $item_id => $item_values){
        // Getting the product ID
        $product_id = $item_values['product_id'];
        // displaying the product ID
        echo '<p>Product ID: '.$product_id.'</p>';
    }
}

这个问题的严格答案是把'p'=>$post_id'改成'post__in' => array($post_id)

...但真正的答案是,如果有人走这条路,解析电子邮件要容易得多,woocommerce 已经为您完成了大部分工作。沿途还有其他陷阱; 1. post 受到保护,订单注释在摘录中,因此无法显示(我可以将它们移动到元但是......) 2. 订单项目在评论中,然后必须循环解析以产生有意义的输出,所以我不妨直接解析电子邮件。