WP_Query 和 WooCommerce 订单有未决状态问题

WP_Query and WooCommerce orders with pending status issue

我无法获取状态为 wc-pending / Pending Payment 的订单对象。它只是 returns 所有订单对象:

$my_course_query = new WP_Query( array(
    'post_type'     => 'shop_order',
    'post_status'   => 'wc-pending',
    'posts_per_page'      => -1
) );

Your code Is just working perfectly as expected, in frontend, I have test it and it output only orders with **pending status. So I can't tell what is your issue as your question is not detailed.

I have found this note on WordPress WP_Query reference that could be useful:
Note: Ticket #18408 For querying posts in the admin, consider using get_posts() as wp_reset_postdata() might not behave as expected.

一般来说,我不使用 WP_Query() 来处理客户订单,但 wc_get_orders() (或 get_posts() 这样:

$customer_orders = wc_get_orders( array(
    'limit'    => -1,
    'status'   => 'pending'
) );

// Iterating through each Order with pending status
foreach ( $customer_orders as $order ) {

    // Going through each current customer order items
    foreach($order->get_items() as $item_id => $item_values){
        $product_id = $item_values['product_id']; // product ID

        // Order Item meta data
        $item_meta_data = wc_get_order_item_meta( $item_id );

        // Some output
        echo '<p>Line total for '.wc_get_order_item_meta( $item_id, '_line_total', true ).'</p><br>';
    }
}

这也适用于获取订单对象。

相关文档:wc_get_orders and WC_Order_Query

I fixed this weird issue by simply using custom query.

不知何故添加 'post_status' => 'wc-pending' 实际上并没有改变查询,但如果我使用 'post_status' => 'pending',查询就会改变。

所以我所做的是使用该自定义查询并将 pending 修改为 wc-pending

我在调试时遇到了同样的问题(返回所有订单)。

将 debug-code 包装成一个动作有助于输出预期的数据:

add_action( 'init', 'debug_init' );

function debug_init() {

    $custom_query_args = array(
        "fields" => "ids",
        "post_type" => "shop_order",
        "post_status" => array('wc-processing'),
        "posts_per_page" => "-1",
        "offset" => "0",
        "date_query" => [
                "before" => "2020-09-10 23:59",
                "after" => "1970-01-01 00:00",
                "inclusive" => "1"
        ],
        "order" => "DESC"
    );


    $debugQuery = new WP_Query( $custom_query_args );
    $order_ids   = $debugQuery->posts;

    print_r($order_ids);

    die();
}