Reputation: 73
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!
Upvotes: 0
Views: 284
Reputation: 6612
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;
}
Upvotes: 1