pre_user_query meta_query admin user list

I’m attempting to use pre_user_query' to change the query to include somemeta_query` variables.

My goal is to only display users in the user list if they share a common meta_value with the current logged in user…

function modify_user_list($query){
    $user = wp_get_current_user();

    if( ! current_user_can( 'edit_user' ) ) return $query;

    $user_id = $user->ID; 
    $user_branch_number = get_user_meta($user_id, 'user_branch_number', true);

    $query->query_vars['meta_key'] = 'user_branch_number';
    $query->query_vars['meta_value'] = $user_branch_number; 
    $query->query_vars['meta_compare'] = '=';

}
add_action('pre_user_query', 'modify_user_list');

If I print_r the query it will show that the query_vars have been updated appropriately, but the user list in the admin panel is unaffected – same old list of every single user.

1 Answer
1

You are using pre_user_query according to WordPress documentation

Fires after the WP_User_Query has been parsed, and before the query is
executed

Then you should use pre_get_users just like pre_get_posts when your arguments have some meaning to WordPress.

pre_get_users Fires before the WP_User_Query has been parsed

Replace your hook with

add_action('pre_get_users', 'modify_user_list');

Leave a Comment