使用PHP在WordPress中设置注释计数格式


Formating Comment Count in WordPress with PHP

我在Wordpress的前端使用了以下php来显示我的博客总共有多少条评论。比如说要渲染显示这样的效果:1265788

<?php
$comments_count = wp_count_comments();
echo number_format($comments_count->total_comments);
?>

我想做的是更好地格式化数字。因此,它不会说我有1265788条评论,而是说我有12.65亿条评论。

我按照另一篇帖子的建议尝试了以下代码,但也不起作用。echo是完整的数字。

<?php
$comments_count = wp_count_comments();
if ($comments_count->total_comments < 1000000) {
    // Anything less than a million
    $n_format = number_format($comments_count->total_comments);
    echo $n_format;
} else if ($comments_count->total_comments < 1000000000) {
    // Anything less than a billion
    $n_format = number_format($comments_count->total_comments / 1000000, 3) . 'M';
    echo $n_format;
} else {
    // At least a billion
    $n_format = number_format($comments_count->total_comments / 1000000000, 3) . 'B';
    echo $n_format;
}
?>

所以不,这不是一个重复的问题。以前的答案对我来说绝对没有帮助。我试着完全按照答案说的去做,得到的输出是完整的数字,就像最初的顶部代码给我的一样。

任何人都知道我如何做到这一点,请给我看一个样品。

谢谢!

实际上,上面的代码运行良好,输出为1.266M

硬编码示例:

$number = 1265788;
if ($number < 1000000) {
    // Anything less than a million
    $n_format = number_format($number);
    echo $n_format;
} else if ($number < 1000000000) {
    // Anything less than a billion
    $n_format = number_format($number / 1000000, 3) . 'M';
    echo $n_format;
} else {
    // At least a billion
    $n_format = number_format($number / 1000000000, 3) . 'B';
    echo $n_format;
}

动态:

$comments_count = wp_count_comments();
$number = $comments_count->total_comments;
if ($number < 1000000) {
    // Anything less than a million
    $n_format = number_format($number);
    echo $n_format;
} else if ($number < 1000000000) {
    // Anything less than a billion
    $n_format = number_format($number / 1000000, 3) . 'M';
    echo $n_format;
} else {
    // At least a billion
    $n_format = number_format($number / 1000000000, 3) . 'B';
    echo $n_format;
}