0

How are you?

I have a blog which have 20 authors. I want to write code to show the 5 author who have more posts.

like this:

Adam (10 Posts) Khal (8 Posts) Yous (5 Posts) Moha (3 Posts) Yousef (1 Post)

but I don't know how can do it that

2 Answers 2

6

Are you using WordPress 3.1+? There's a nice get_users() function that'll do the trick! However, you will need a little magic to boot:

add_action( 'pre_user_query', 'wpse_11832_pre_user_query' );

/**
 * Adds "post_count" to the SELECT clause. Without this, the "post_count"
 * property for users will be undefined.
 * 
 * @param object $wp_user_query
 */
function wpse_11832_pre_user_query( $wp_user_query ) {
    if ( $wp_user_query->query_vars['orderby'] == 'post_count' )
        $wp_user_query->query_fields .= ', post_count';
}

And example usage:

<?php foreach ( get_users( 'order=DESC&orderby=post_count&number=5' ) as $user ) : ?>

    <?php echo $user->display_name; ?> (<?php echo $user->post_count; ?> Posts)

<?php endforeach; ?>

Important: You must order by post_count, otherwise it will be undefined.

6
  • thank you , but the code didn't work. Fatal error: Call to undefined function get_users() in /home/abosami/public_html/wp-content/plugins/wp-php-widget/wp-php-widget.php(52) : eval()'d code on line 1.
    – AboSami
    Mar 12, 2011 at 15:52
  • Note: I include it in PHP widget
    – AboSami
    Mar 12, 2011 at 15:52
  • 1
    As he said, make sure you're running 3.1, otherwise this function won't work.
    – Pippin
    Mar 12, 2011 at 16:22
  • 1
    Upgrade to 3.1! Mar 12, 2011 at 16:58
  • This is not working in wordpress 3.4.2. <?php echo $user->post_count; ?> is blank even if users have posts. I'm unable to debug it.
    – Blue
    Oct 24, 2012 at 15:35
0

Work, i try ussing...

<?php foreach ( get_users( 'order=DESC&orderby=post_count&number=5' ) as $user ) : ?>

<?php 
    if ($user->post_count > 0) {
        echo $user->display_name.' ( '. $user->post_count .' Posts)<br/>';
    }
?> 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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