I’m trying to add a search bar to the WooCommerce Orders page on the frontend customer account dashboard for specific user roles (don’t want showing for all customers).
I feel like I’m close, but the below code is just not working. I only need to search by order number. This code produces a "No order has been made yet." result despite there being many orders in my test account.
I also notice that when conducting the search, the URL doesn’t change like I’d normally expect it to so I’m wondering if that’s a tip-off to what’s wrong with the code…?
function add_search_to_orders() {
$allowed_roles = array('administrator', 'shop_manager');
$user = wp_get_current_user();
$user_roles = (array) $user->roles;
if (array_intersect($allowed_roles, $user_roles)) {
echo '<form method="post" id="orders-search-form">
<input type="text" name="search_orders" placeholder="Search by order number..." />
<input type="hidden" name="order_status" value="wc-completed" />
<button type="submit">Search</button>
</form>';
}
}
add_action('woocommerce_before_account_orders', 'add_search_to_orders');
function search_all_orders_by_number($args) {
if (isset($_POST['search_orders']) && !empty($_POST['search_orders'])) {
$search_term = sanitize_text_field($_POST['search_orders']);
$args['meta_query'] = array(
array(
'key' => '_order_number',
'value' => $search_term,
'compare' => 'LIKE'
)
);
}
return $args;
}
add_filter('woocommerce_my_account_my_orders_query', 'search_all_orders_by_number');
2
Answers
For those that stumble on this and are interested, here is the final code I got to work successfully with a WC HPOS store. Worked perfectly and I added some other mods to have a reset ability.
Your provided code works just fine for "_order_number" meta_key, but since High Performance Order Storage is now enabled by default and uses a WooCommerce custom database table, all your order numbers need to be saved using
WC_Data
add_meta_data()
orupdate_meta_data()
methods, instead of using WordPress post meta functions.See: Order custom field added via checkout is lost after WooCommerce HPOS sync