FB Pixel

Displaying WordPress authors sorted by recent activity

A few weeks ago I ran into someone on the WordPress StackExchange wanting to sort his list of authors by recent activity – the author with the most recently published article first, etc. This type of sorting isn’t currently possible using the get_users() function(codex), nor the WP_User_Query class (codex), but it can be done – here’s how:

Let’s assume you currently have something similar to the below in your author.php (or archive.php) theme file:

$users = get_users(); foreach ( $users as $user ) {      // HTML for each author using the $user object }

You can make use of the $wpdb global object (codex) to make a direct SQL query that returns a list of author IDs sorted by recent activity:

global $wpdb; $user_ids = $wpdb->get_results(     "     SELECT DISTINCT post_author     FROM $wpdb->posts     ORDER BY post_date DESC      " );

You can then loop through this list of author IDs, retrieve the $user object with the get_user_by() function (codex), and write out your HTML save as before:

if ( $user_ids ) {     foreach ( $user_ids as $user_id ) {     $user = get_user_by( 'id', $user_id );          // HTML for each author using the $user object     } }