使用PHP格式化WordPress中的注释计数

时间:2013-07-07 19:28:23

标签: php wordpress number-formatting

我在前端使用Wordpress中的以下php来显示我的博客有多少评论总数。所以说例如会渲染以显示这种效果:1,265,788

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

我想做的是更好地格式化数字。所以我没有说1,265,788条评论,而是说我有1,265M评论。

我按照其他帖子的建议尝试了以下代码,但也无效。它回显了全数。

<?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 个答案:

答案 0 :(得分:1)

实际上上面的代码工作正常,输出为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;
}