Number format for wp_count_posts()

I’m trying to format my post my total post count in the header of my site. I have the number in there but would like it to format with the commas eg 1,500 not 1500. I know this is probably really basic but I’m still learning.. any help would be much appreciated. Cheers

functions.php

function wpb_total_posts() { 
$total = wp_count_posts()->publish;
echo '' . $total;
}

Header.php

<?php wpb_total_posts(); ?>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use the PHP function number_format().

function wpb_total_posts() { 
    $total = wp_count_posts()->publish;
    echo number_format( 
        $total, // your number
        0,      // number of decimal points
        '.',    // decimal point separator
        ','     // thousands separator
    );
}

Or, because you are using the default values anyway, you can shorten the function to:

function wpb_total_posts() { 
    echo number_format( wp_count_posts()->publish );
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x