Using WordPress ‘pre_user_query’ PHP action

The pre_user_query WordPress PHP action fires after the WP_User_Query has been parsed and before the query is executed.

Usage

add_action('pre_user_query', 'my_custom_pre_user_query');
function my_custom_pre_user_query($query) {
    // Your custom code here
    return $query;
}

Parameters

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

More information

See WordPress Developer Resources: pre_user_query

Examples

Modify the User Query to Order by Display Name

This example shows how to modify the user query to order the results by display name.

add_action('pre_user_query', 'order_users_by_display_name');
function order_users_by_display_name($query) {
    $query->query_orderby = 'ORDER BY display_name ASC';
}

Exclude a Specific User Role from the Query

This example demonstrates how to exclude users with a specific role from the query.

add_action('pre_user_query', 'exclude_user_role_from_query');
function exclude_user_role_from_query($query) {
    global $wpdb;
    $query->query_where .= " AND {$wpdb->users}.ID NOT IN (SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = '{$wpdb->prefix}capabilities' AND meta_value LIKE '%\"editor\"%')";
}

Limit the Number of Users Returned

This example limits the number of users returned by the query to 5.

add_action('pre_user_query', 'limit_users_returned');
function limit_users_returned($query) {
    $query->query_limit = 'LIMIT 5';
}

Search Users by Custom Meta Field

This example demonstrates how to search users based on a custom meta field value.

add_action('pre_user_query', 'search_users_by_custom_meta_field');
function search_users_by_custom_meta_field($query) {
    global $wpdb;
    $search = 'John Doe';
    $query->query_from .= " LEFT JOIN {$wpdb->usermeta} ON ( {$wpdb->users}.ID = {$wpdb->usermeta}.user_id )";
    $query->query_where .= " AND {$wpdb->usermeta}.meta_key = 'custom_field' AND {$wpdb->usermeta}.meta_value LIKE '%" . $search . "%'";
}

Filter Users by Registration Date

This example filters users by their registration date, only showing users registered within the last 30 days.

add_action('pre_user_query', 'filter_users_by_registration_date');
function filter_users_by_registration_date($query) {
    global $wpdb;
    $query->query_where .= " AND {$wpdb->users}.user_registered >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
}