this code works great! the problem is that this code also hide the current user (if administrator) so what i trying to to do is hide all Administrators except current user.

i need help to edit sql to make this work with "$user_ID"

function isa_pre_user_query($user_search) {
  $user = wp_get_current_user();
  //if (!current_user_can('administrator')) { // Is Not Administrator - Remove Administrator
    global $wpdb;
    $user_ID = get_current_user_id();
    $user_search->query_where = 
        str_replace('WHERE 1=1', 
            "WHERE 1=1 AND {$wpdb->users}.ID IN (
                 SELECT {$wpdb->usermeta}.user_id FROM $wpdb->usermeta 
                    WHERE {$wpdb->usermeta}.meta_key = '{$wpdb->prefix}capabilities'
                    AND {$wpdb->usermeta}.meta_value NOT LIKE '%administrator%')", 

Quoting from the WordPress VIP Development Best Practices:

Remember that the database is not a tool box. Although you might be able to perform a lot of work on the database side, your code will scale much better by keeping database queries simple and performing necessary calculations and logic in PHP.

That said, you might just try to get all non-admin users and then add the current user to the results, if that user has admin capabilities.

You can easily achieve this using higher-level WordPress functions:

    /* get all non-admin users */
    $args = array( 
        'meta_key'     => 'wp_capabilities', 
        'meta_value'   => 'Administrator', /* you better check for a capability, not a role */
        'meta_compare' => 'NOT LIKE'
    $user_query = new WP_User_Query( $args );

    /* if current user is admin, get its user object */
    $current_admin_user = current_user_can( 'activate_plugins' ) ? wp_get_current_user() : null;

    /* merge non-admin users with current admin-user */
    $results = $user_query->get_results();
    $results[] = $current_admin_user;

    /* update the user query */
    $user_query->__set( 'results', $results );
    $user_query->__set( 'total_users', count( $results ));

    /* do whatever you want */
  • Hi @Jan Beck, i try this code but i can't get it work with user list in users.php i tried to use add_action('pre_user_query','pre_user_query'); but this not working. – need-help Dec 31 '14 at 7:24
  • so when you say users.php you mean wp-admin/users.php? Are we talking about the users admin panel where you want to hide the admins except the logged-in ones? – Jan Beck Dec 31 '14 at 15:55

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.