Using WordPress ‘pre_count_users’ PHP filter

The pre_count_users filter allows you to change the user count before WordPress runs any queries on it. By returning a non-null value, you can make the count_users() function return early.

Usage

add_filter('pre_count_users', 'your_custom_function', 10, 3);

function your_custom_function($result, $strategy, $site_id) {
    // your custom code here

    return $result;
}

Parameters

  • $result (null|array): The value to return instead. Default is null to continue with the query.
  • $strategy (string): The computational strategy to use when counting the users. Accepts either ‘time’ or ‘memory’. Default is ‘time’.
  • $site_id (int): The site ID to count users for.

More information

See WordPress Developer Resources: pre_count_users

Examples

Return a fixed user count

In this example, we return a fixed user count of 500, bypassing the count_users() query.

function fixed_user_count($result) {
    return 500;
}
add_filter('pre_count_users', 'fixed_user_count');

Adjust user count by a factor

In this example, we adjust the user count by multiplying it by a factor of 2.

function adjust_user_count($result, $strategy, $site_id) {
    $actual_count = count_users($strategy, $site_id);
    $adjusted_count = $actual_count * 2;

    return $adjusted_count;
}
add_filter('pre_count_users', 'adjust_user_count', 10, 3);

Exclude inactive users

In this example, we exclude inactive users from the user count.

function exclude_inactive_users($result, $strategy, $site_id) {
    $args = array(
        'blog_id' => $site_id,
        'role' => '',
        'meta_key' => 'last_activity',
        'meta_value' => strtotime('-1 month'),
        'meta_compare' => '>',
    );
    $user_query = new WP_User_Query($args);

    return $user_query->get_total();
}
add_filter('pre_count_users', 'exclude_inactive_users', 10, 3);

Return user count only for a specific role

In this example, we return the user count for a specific role, e.g., ‘editor’.

function count_editors($result, $strategy, $site_id) {
    $args = array(
        'blog_id' => $site_id,
        'role' => 'editor',
    );
    $user_query = new WP_User_Query($args);

    return $user_query->get_total();
}
add_filter('pre_count_users', 'count_editors', 10, 3);

Change computational strategy

In this example, we change the computational strategy to ‘memory’ instead of the default ‘time’.

function change_strategy($result, $strategy, $site_id) {
    $strategy = 'memory';
    $count = count_users($strategy, $site_id);

    return $count;
}
add_filter('pre_count_users', 'change_strategy', 10, 3);