WordPress – Filter users list count

There’s really not a ton of great hooks for this one. It uses the WP_Users_List_Table class and the views_users hook, which you could use to parse and replace the number.

The hook gives us an array of links like so (even though it’s a flat array, the value is an link).

Array
(
    [all] => All (4)
    [administrator] => Administrator (2)
    [editor] => Editor (2)
)

IMO the easiest thing to do is just regex the (2) and run a str_replace().

/**
 * Modify the role list views at the top of users.php
 * 
 * @param array $user_roles
 * 
 * @return array $user_roles
 */
add_filter( 'views_users', function( $user_roles ) {
    
    $roles = array(
        'administrator' => -1,
        'editor'        => +1,
    );

    foreach( $user_roles as $slug => $link ) {

        // Skip - Role slug does not exist in our array.
        if( ! isset( $roles[ $slug ] ) ) { continue; }

        // $matches = array( 0 => '(123)', 1 => 123 )
        preg_match('/\((\d+)\)/', $link, $matches );

        // Skip - The regex did not get our matches
        if( count( $matches ) < 2 ) { continue; }

        // Modify
        $original_number = absint( $matches[1] );
        $modified_number = $original_number + $roles[ $slug ];
        
        // Replace
        $user_roles[ $slug ] = str_replace( 
            '(' . $original_number . ')', 
            '(' . $modified_number . ')',
            $user_roles[ $slug ]
        );

    }
    
    return $user_roles
    
} );

This of course won’t modify the list of users in the Users table. You would need to use pre_user_query for that sort of thing.


Alternatively, the view does use count_users(), and there is a pre_count_users hook, but you have to short-circuit it and count the users w/ roles yourself.

techhipbettruvabetnorabahisbahis forumuedueduedueduedusedueduedueduedus