Categories
Posted in: How to, Wordpress

How to add a User ID column to WordPress User List Table

Have you ever thought, “It would be nice to know the user ID?”

We was thinking the same thing.

We will show you how to add a new column to the WordPress user list table so you will now know what a user’s ID is.

First, we need to add the new column to the list of columns.

// This adds a new column to the user list table to show us the ID of the user
add_filter('manage_users_columns', 'jematrix_add_user_id_column');
function jematrix_add_user_id_column($columns) {
    $columns['user_id'] = 'User ID';
    return $columns;
}

The function sets our new column and we name it “User ID”. We then use the filter “manage_users_columns” to register our new column so WordPress knows it’s there. Lastly, we return the columns for output.

Next, we get the user’s ID number to be displayed for each user.

add_action('manage_users_custom_column',  'jematrix_show_user_id_column_content', 10, 3);
function jematrix_show_user_id_column_content($value, $column_name, $user_id) {
    $user = get_userdata( $user_id );
	if ( 'user_id' == $column_name )
		return $user_id;
    return $value;
}

In this function, we get the user ID with get_userdata($user_id) and then return that ID using the action “manage_users_custom_column” and set the priority.

Now, if you want to sort the new column add this next function.

add_filter( 'manage_users_sortable_columns', 'jematrix_user_id_column' );
function jematrix_user_id_column( $columns ) {
$columns['user_id'] = 'id';

//To make a column 'un-sortable' remove it from the array
// Example
//unset($columns['date']);

return $columns;
}

In this function, we tell WordPress that our column is sorted by the id that WordPress assigns a user. Then we hook into the filter “manage_users_sortable_columns”. This is unique as per the docs it is manage_{$this->screen->id}_sortable_columns. So in other words { } is users because we are on the user’s page. If we were on the all posts page it would be manage_edit-post_sortable_columns.

We hope this article helps you in some fashion.

References:
https://developer.wordpress.org/reference/hooks/manage_users_custom_column/
https://developer.wordpress.org/reference/hooks/manage_users_custom_column/
https://developer.wordpress.org/reference/hooks/manage_this-screen-id_sortable_columns/

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.