I am implementing a section in my website to get the top 5 authors using this code.
function ranked_authors(){
$usrs = get_users('role=contributor');
$countarr = array();
foreach ($usrs as $usr) {
$post_views = total_no_of_post_views($usr->ID);
$countarr[$usr->ID] = $post_views;
}
arsort($countarr);
$i=1;
foreach($countarr as $id => $pcount){
if($i<=5){
$div_media = '<div class="media clearfix">
<div class="media-left">';
$author_link = get_author_posts_url($id);
$author_name = get_the_author_meta('display_name',$id);
$avatar = get_avatar_url( $id, 'size=50' );
$div_media .= '<a href="'.$author_link.'">'.get_avatar($id, 'size=50').'
<span class="rank">'.$i.'</span>
</a>
</div>
<div class="media-body">';
$div_media .= '<h4 class="media-heading"><a href="'.$author_link.'">'.$author_name.'</a></h4>'.$pcount.' Total Views</div>
</div>';
echo $div_media;
$i++;
}
}
}
I am having more than 4000 post on my blog so this query is taking so much time to execute and it almost taking 10 second to process and return the data from the server. Then i thought of Doing it in ajax way.
But there is a problem in my code that it doesn't return me any data in ajax request when i am returning(return)
the result but if i echo
this function then it returns me the data through ajax request.
I don't know but is wrong i am doing.
I want to sort the authors according to the total no of post views.this is the function i am using to count total no of post views.
function total_no_of_post_views($author_id){
$sumViews = 0;
$args = array(
'author' => $author_id,
'post_type' => array('communityposts','post','video'),
'posts_per_page'=> -1
);
$author_query = new WP_Query( $args );
if( $author_query->have_posts() ) : while( $author_query->have_posts() ) : $author_query->the_post();
$sumViews += get_post_meta( get_the_ID(), 'cv_post_views_count', true );
endwhile; endif;
wp_reset_postdata();
return $sumViews;
}
My final requirements is to calculate top 5 authors sorted according to the total no. of post views value of their published posts.