Using WordPress ‘found_users_query’ PHP filter

The found_users_query WordPress PHP filter modifies the SELECT FOUND_ROWS() query for the current WP_User_Query instance.

Usage

add_filter('found_users_query', 'my_custom_found_users_query', 10, 2);
function my_custom_found_users_query($sql, $query) {
    // your custom code here
    return $sql;
}

Parameters

  • $sql (string): The SELECT FOUND_ROWS() query for the current WP_User_Query.
  • $query (WP_User_Query): The current WP_User_Query instance.

More information

See WordPress Developer Resources: found_users_query

Examples

Limit total number of users

Modify the query to limit the total number of users to 100.

add_filter('found_users_query', 'limit_total_users', 10, 2);
function limit_total_users($sql, $query) {
    $sql .= " LIMIT 100";
    return $sql;
}

Exclude users with specific email domain

Exclude users with emails from the “example.com” domain.

add_filter('found_users_query', 'exclude_specific_email_domain', 10, 2);
function exclude_specific_email_domain($sql, $query) {
    $sql .= " AND user_email NOT LIKE '%@example.com'";
    return $sql;
}

Show only users with specific meta key

Display users who have a specific meta key “my_meta_key”.

add_filter('found_users_query', 'show_users_with_meta_key', 10, 2);
function show_users_with_meta_key($sql, $query) {
    global $wpdb;
    $sql .= " AND EXISTS (SELECT * FROM {$wpdb->usermeta} WHERE user_id = {$wpdb->users}.ID AND meta_key = 'my_meta_key')";
    return $sql;
}

Exclude users with specific role

Exclude users with the “subscriber” role.

add_filter('found_users_query', 'exclude_users_with_role', 10, 2);
function exclude_users_with_role($sql, $query) {
    global $wpdb;
    $sql .= " AND {$wpdb->users}.ID NOT IN (SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = '{$wpdb->prefix}capabilities' AND meta_value LIKE '%subscriber%')";
    return $sql;
}

Show users with custom field value

Display users who have a custom field “my_custom_field” with the value “yes”.

add_filter('found_users_query', 'show_users_with_custom_field', 10, 2);
function show_users_with_custom_field($sql, $query) {
    global $wpdb;
    $sql .= " AND EXISTS (SELECT * FROM {$wpdb->usermeta} WHERE user_id = {$wpdb->users}.ID AND meta_key = 'my_custom_field' AND meta_value = 'yes')";
    return $sql;
}