Woocommerce wp_query 通过 ID 获取订单

Chr*_*ink 3 php wordpress foreach orders woocommerce

我正在尝试生成订单数据的简单输出。第一步是 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;
Run Code Online (Sandbox Code Playgroud)

它为产品提供所有订单的列表,如果我设置'p' => $post_idwhere$post_id是有效的帖子 ID,则查询不返回任何内容。

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

或者,是否有一种 Woocommerce 方式来生成具有如下布局的纯页面;

Order ID: 836
Order Status: ....
Run Code Online (Sandbox Code Playgroud)

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

Loi*_*tec 5

更新 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'];
    // .../...
}
Run Code Online (Sandbox Code Playgroud)

更新 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>';
    }
}
Run Code Online (Sandbox Code Playgroud)