dongwei4444 2013-07-07 19:28
浏览 15
已采纳

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

I have the following php I use in Wordpress on the frontend to display how many total comments my blog has. So say for example would render to display something to this effect: 1,265,788

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

What I would like to do is format the number better. So instead of it saying I have 1,265,788 comments, it will say I have 1,265M comments.

I tried the following code as recommended by another post, but does not work either. It echo's the full number.

<?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;
}
?>

So no, this is not a duplicate question. Previous answers are of absolute no help to me. I tried exactly like the answers said and the output I get is the full number like the original top code gives me.

Anyone have an idea how I can achieve this and can show me a sample please.

Thank you!

  • 写回答

1条回答 默认 最新

  • dth96108 2013-07-07 19:51
    关注

    Actually above code is working fine and output is 1.266M

    Hard coded example:

    $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;
    }
    

    Dynamic:

    $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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码