您可以使用count\\u user\\u posts()函数获取特定作者的帖子总数。通过特定作者循环浏览所有帖子,您可以获得每个帖子的赞数,并将其存储/添加到一个变量中。这里有一个函数。
<?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;
}
?>
在希望作者页面上显示平均喜欢数的位置调用avg\\u num\\u of\\u likes()。
@Harman Preet您可以使用一个附加函数来实现这一点。和更改$avgLikes = $number_of_posts / $sumLikes;
到$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;
}
参考号:
https://stackoverflow.com/questions/4371059/shorten-long-numbers-to-k-m-b