4

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.

2
  • You aren't returning the $query after you change the vars.
    – shanebp
    Commented Apr 21, 2015 at 20:06
  • 3
    @shanebp in this hook query has been passed by reference so there is no need to return the query.
    – Sumit
    Commented Apr 21, 2015 at 20:09

1 Answer 1

5

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');

6
  • Thank you, I didn't realize I was using the wrong hook !
    – sirmdawg
    Commented Apr 22, 2015 at 22:34
  • any idea how to change the results above the list ? I still se e "100" subscribers, but only 5 are shown ( the five that should show )
    – sirmdawg
    Commented Apr 22, 2015 at 22:51
  • @mkirkpatrick I din't get your question ? When I tested that snippet it was working fine! Can you please brief your problem a bit ?
    – Sumit
    Commented Apr 23, 2015 at 7:23
  • The results int the list work as intended, but for some reason the sorting options above the list still include the total number of users.
    – sirmdawg
    Commented Apr 24, 2015 at 19:46
  • 2
    I got a filter views_users but no luck as there is no global variable for current user query! so how can we alter the count ? And there is no filter in count_users() :(
    – Sumit
    Commented Apr 25, 2015 at 11:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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