Aller au contenu
FR

Sort WordPress users by ID

Sort Wordpress users by ID
Version audio de cet article

This tutorial will show you how to sort WordPress users by ID and DESC. Thanks to the pre_get_posts hook, it will allow us to custom a query for and posts types. The pre_get_posts can generate WordPress admin results; i.e. on the website’s front end.In this case, we will be using pre_get_users which is designed to return users.

In the example below, we’ll be looking to sort our WordPress users into a table. First off, we need a condition that indicates that if the user isn’t an Admin, do nothing.

Then we use two arguments: the orderby ID and the order DESC.
Voilà! Your users are now sorted at the top of the table with the newly created users first.

///////////////////////////// Admin users order by ID and DESC Pre Get Users //////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////
 
function sitebook_order_users_by_id( $query ) {
 
   //Check that we are in admin otherwise return
   if( !is_admin() ) {
      return;
   }
 
   // We are changing the query_vars to reorder
   $query->query_vars['orderby'] = 'ID';
   $query->query_vars['order']   = 'DESC';
 
   // We need to remember to return the altered query.
   return $query;
}
// Lets apply our function to hook.
add_action( 'pre_get_users', 'sitebook_order_users_by_id' );