I'm asked by my friend to create a widget for his multiauthor blog. He wants to list 3 authors with the most total post view from their posts. I've got the job done for the post view using post metadata. But I'm confused on querying the authors with that criteria. Any idea?
Thanks for the help.
[update] I'm using this codes and its work. Is there any simpler version?
global $wpdb;
$topuser = array();
// query all posts by each user
$users = $wpdb->get_results("SELECT ID FROM $wpdb->users ORDER BY ID");
foreach ( $users as $user ) {
$query = get_posts( array('author' => $user->ID ));
$counter = 0;
// get each post of a user
foreach ( $query as $post ){
$views = absint( get_post_meta( $post->ID, 'post_views_count', true ) );
$counter += $views;
}
$topuser[] = array( 'id' => $user->ID, 'views' => $counter);
wp_reset_query();
}
// function to sort array based on views count
function sortViews($a, $b) {
return $b['views'] - $a['views'];
}
usort($topuser, 'sortViews'); // sort the array
$output = array_slice($topuser, 0, 3); // slice the array by limit 3
// output the result: user, total postview count, latest post
foreach ($output as $user){
$profile = get_userdata($user['id']);
$query = get_posts( array('author' => $user['id'], 'numberposts' => 1 ));
echo '<p>' . $profile->user_nicename .' ('. $user['views'] .')</p>';
foreach ( $query as $post ){
echo '<a href="' . $post->post_name . '">' . $post->post_title . '</a>';
echo get_post_meta($post->ID, 'post_views_count', true);
}
}