Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I use the following code for getting the authors of in my multi-author blog and order them by their post count. I want to order them by the date of their last post

$authors = get_users('role=author&orderby=post_count&order=DESC');
share|improve this question
    
That's not possible using get_users –  Tom J Nowell Apr 18 '13 at 10:27
    
any way to get that? –  Midhun Apr 18 '13 at 11:28
add comment

1 Answer

up vote 3 down vote accepted

Put this in your functions.php:

function get_users_ordered_by_post_date($args = '') {
    // Prepare arguments
    if (is_string($args) && '' !== $args)
        parse_str($args, $args);
    $asc = (isset($args['order']) && 'ASC' === strtoupper($args['order']));
    unset($args['orderby']);
    unset($args['order']);

    // Get ALL users
    $users = get_users($args);
    $post_dates = array();
    if ($users) {
        // For EACH user ...
        foreach ($users as $user) {
            $ID = $user->ID;

            // ... get ALL posts (per default sorted by post_date), ...
            $posts = get_posts('author='.$ID);
            $post_dates[$ID] = '';

            // ... then use only the first (= newest) post
            if ($posts) $post_dates[$ID] = $posts[0]->post_date;
        }
    }

    // Sort dates (according to order), ...
    if (! $asc)
        arsort($post_dates);

    // ... then set up user array
    $users = array();
    foreach ($post_dates as $key => $value) {
        // $user = get_userdata($key);
        // $users[] = $user->ID;
        $users[] = get_userdata($key);
    }
    return $users;
}

The above function returns an array of WP_User objects.

// EDIT: the function now supports an args parameter (either string or array). The output is ordered with respect to order=DESC and order=ASC. The order_by parameter is remove (we want to order by last post date anyway), all other parameters are passed to get_users.

Now, you can use the function like so:

get_users_ordered_by_post_date();

or

get_users_ordered_by_post_date('role=author');

or

// order by OLDEST post first
get_users_ordered_by_post_date('role=administrator&order=ASC');
share|improve this answer
1  
Thank you verymuch for that –  Midhun Apr 18 '13 at 11:32
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.