Home / Admin / Sort User ID
Duplicate Snippet

Embed Snippet on Your Site

Sort User ID

Make the User ID column sortable in the WordPress admin users table. First register the column, add its content, define it as sortable, and then hook into the query to perform the sort.

Code Preview
php
<?php
// 1. Add the User ID column to the users table
add_filter('manage_users_columns', 'add_user_id_column');
function add_user_id_column($columns) {
    // Insert 'user_id' column after the checkbox column
    $new_columns = array();
    foreach ($columns as $key => $value) {
        $new_columns[$key] = $value;
        if ($key === 'cb') {
            $new_columns['user_id'] = 'ID';
        }
    }
    return $new_columns;
}
// 2. Populate the User ID column with the actual ID
add_action('manage_users_custom_column', 'display_user_id_column_content', 10, 3);
function display_user_id_column_content($output, $column_name, $user_id) {
    if ($column_name === 'user_id') {
        return $user_id;
    }
    return $output;
}
// 3. Make the User ID column sortable
add_filter('manage_users_sortable_columns', 'make_user_id_column_sortable');
function make_user_id_column_sortable($columns) {
    $columns['user_id'] = 'ID';
    return $columns;
}
// 4. Handle the sorting logic for the User ID column
add_action('pre_user_query', 'sort_users_by_user_id');
function sort_users_by_user_id($user_search) {
    global $wpdb;
    
    // Check if we are on the users admin page
    $current_screen = get_current_screen();
    if ($current_screen->id !== 'users') {
        return;
    }
    $vars = $user_search->query_vars;
    
    // If sorting by our custom column ID
    if (isset($vars['orderby']) && $vars['orderby'] === 'user_id') {
        // WordPress handles 'ID' natively, so we just ensure the orderby is set correctly
        $user_search->query_orderby = ' ORDER BY ' . $wpdb->users . '.ID ' . (isset($vars['order']) ? strtoupper($vars['order']) : 'ASC');
    }
}   

Comments

Add a Comment