You can use count_user_posts() function to get the number of total posts for specific author. With looping through all posts by the specific author, you can get the number of likes on each post and store it/add it in one variable. Here is a function for that.
<?php
function avg_num_of_likes() {
$author = get_user_by( 'id', get_query_var( 'author' ) );
$author_id = $author->ID;
$number_of_posts = count_user_posts( $author_id );
$sumLikes = 0;
$avgLikes = 0;
$args = array(
'author' => $author_id
);
$author_query = new WP_Query( $args );
if( $author_query->have_posts() ) : while( $author_query->have_posts() ) : $author_query->the_post();
$sumLikes += get_post_meta( get_the_ID(), 'cv_posts_view', true );
endwhile; endif;
wp_reset_postdata();
$avgLikes = $number_of_posts / $sumLikes;
return $avgLikes;
}
?>
Call avg_num_of_likes() in the place where you want the average number of likes to be displayed on the author’s page.
@Harman Preet
You can use an additional function for that. And change $avgLikes = $number_of_posts / $sumLikes;
to $avgLikes = custom_number_format( $number_of_posts / $sumLikes );
.
function custom_number_format($n, $precision = 1) {
if($n < 1000 ) {
$n_format = number_format($n);
}
else if ($n < 1000000) {
// Anything less than a million
$n_format = number_format($n / 1000, $precision) . 'K';
} else if ($n < 1000000000) {
// Anything less than a billion
$n_format = number_format($n / 1000000, $precision) . 'M';
} else {
// At least a billion
$n_format = number_format($n / 1000000000, $precision) . 'B';
}
return $n_format;
}
Ref: https://stackoverflow.com/questions/4371059/shorten-long-numbers-to-k-m-b