3

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.

5

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');
2
  • where handle_by ? your answer didnt fully matched the scenarios and can be further improving – nyconing Jun 22 '20 at 7:11
  • Ahh, true. I have a lot of meta_key with same value while developing it. Fixed to match the scenario. – Permana Jun 23 '20 at 3:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.