Story:
I have custom role Staff
for my WooCommerce shop,
When a Customer create an Order, the Order is assigned a custom meta name handle_by
where the value is a random value of user where role is Staff.
When Staff is login and click WooCoomerce > Orders
, He/She will only see Orders where handle_by
is match current user id.
Problem:
How to filter WooCommerce > Order to only show Order where the custom meta handle_by
is match with current user login.
Solved it, using pre_get_posts
filter and WP_Query->set()
method
function foo_filter_orders($query) {
global $pagenow;
$qv = &$query->query_vars;
$currentUserRoles = wp_get_current_user()->roles;
if (in_array('shop_manager', $currentUserRoles)) {
if ( $pagenow == 'edit.php' &&
isset($qv['post_type']) && $qv['post_type'] == 'shop_order' ) {
$query->set('meta_key', 'handle_by');
$query->set('meta_value', 'shopmanager1');
}
}
return $query;
}
add_filter('pre_get_posts', 'foo_filter_orders');