在 my-orders.php 中检索单个订单

Retrieving single order in my-orders.php

我正在尝试在 my-orders.php 中添加一个搜索表单,用户可以在其中通过输入订单 ID 来搜索订单 table。

目前,我正在检索 1 个客户使用 get_posts 的所有订单:

$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' => 'wc-quotes') ) );

有什么方法可以仅通过订单 ID(在搜索栏中输入的值)检索订单?

我还是 WooCommerce 的新手,所以如果我的解释令人困惑,请原谅我。

使用wc_get_order函数并在参数

中传递你的orderid
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );

$order_data = $order->get_data(); // The Order data

现在您可以使用 $order_data

echo '<pre>'; print_r($order_data); 

参考

https://docs.woocommerce.com/wc-apidocs/function-wc_get_order.html https://docs.woocommerce.com/document/composite-products/composite-products-functions-reference/

您首先需要向您的页面添加一个自定义表单,因为普通搜索栏对此不起作用。

这是一个使用 post 方法的自定义表单,您可以使用:

echo'<form method="post" action="">
    <label>Search an Order ID</label><br>
    <input type="text" name="orderid" value="">
    <input type="submit" name="submit_trusted_list" value="Submit"/>
</form>';

然后由于挂钩过滤器 woocommerce_my_account_my_orders_query 包含在查询订单的代码中,您将使用自定义挂钩函数,其中参数 'post__in' 将使用给定的订单 ID 过滤查询:

add_filter( 'woocommerce_my_account_my_orders_query', 'search_orders_by_id', 20, 1 );
function search_orders_by_id( $args ){
    if( isset($_POST['orderid']) && is_numeric ($_POST['orderid']) ){
        $args['post__in'] = array(intval($_POST['orderid']));
    }
    return $args;
}

代码进入活动子主题(或活动主题)的 function.php 文件。

已测试并有效。

So you will get a filtered list only with the requested order.