Using WordPress ‘pre_get_users’ PHP action

The pre_get_users WordPress PHP action fires before the WP_User_Query has been parsed. The passed WP_User_Query object contains the query variables, which have not yet been converted into SQL.

Usage

add_action('pre_get_users', 'your_custom_function_name');
function your_custom_function_name($query) {
    // Your custom code here
}

Parameters

  • $query (WP_User_Query) – The current instance of WP_User_Query, passed by reference.

More information

See WordPress Developer Resources: pre_get_users

Examples

Exclude a user role from the query

This example shows how to exclude all users with the ‘subscriber’ role from the query.

add_action('pre_get_users', 'exclude_subscribers');
function exclude_subscribers($query) {
    $query->set('role__not_in', 'subscriber');
}

Order users by their last name

This example demonstrates how to order users by their last name, in alphabetical order.

add_action('pre_get_users', 'order_users_by_last_name');
function order_users_by_last_name($query) {
    $query->set('meta_key', 'last_name');
    $query->set('orderby', 'meta_value');
    $query->set('order', 'ASC');
}

Limit users with a specific meta value

In this example, we only retrieve users who have a ‘country’ meta value equal to ‘USA’.

add_action('pre_get_users', 'get_usa_users');
function get_usa_users($query) {
    $meta_query = array(
        array(
            'key' => 'country',
            'value' => 'USA',
            'compare' => '='
        )
    );
    $query->set('meta_query', $meta_query);
}

Include users by email domain

This example retrieves only users who have an email address ending in ‘@example.com’.

add_action('pre_get_users', 'include_users_by_email_domain');
function include_users_by_email_domain($query) {
    $query->set('search', '*@example.com');
    $query->set('search_columns', array('user_email'));
}

Exclude users with a specific ID

In this example, we exclude users with the user IDs 5, 10, and 15 from the query.

add_action('pre_get_users', 'exclude_users_by_id');
function exclude_users_by_id($query) {
    $query->set('exclude', array(5, 10, 15));
}