HowTo – WordPress Displaying The Number Of Posts You Have To Your Visitors

Filed under: Wordpress Tips

wordpress-logoMaking posts on your site is hard work and if you want to display your post count to your visitors WordPress has an easy way built in for you to do it.

When placing this code on your site you should understand that each count and each page view that has a count will require another lookup in your database.

If you have a large number of posts on your site .. in the thousands or tens of thousands you may want to find another method that will make an initial count then add to that number when new posts are made and store it in your options table.

This would reduce load on your server limiting the number of times WordPress has to loop through and count all your posts.

Another solution would be to place this only on your front page.

To add a post count to your website you will need to use the wp_count_posts() Function.

This function can count any content type and display a number found.

You can use it to count Pages or Posts and attachments.

You can also use it to count those posts by status type

publish draft pending

Sample Code

To count all of your posts and list the number in your front page you can use

[php]

<?php

$count_posts = wp_count_posts();
echo "Total Number of Posts $count_posts";

?>

[/php]

To count all of your posts that have been published and not in draft or pending

[php]

<?php

$count_posts = wp_count_posts();

$published_posts = $count_posts->publish;

echo "Number of Published Posts $published_posts";

?>

[/php]

To count all of your pages and not posts you can use:

[php]

<?php

$count_pages = wp_count_posts(‘page’);

echo "Number of Pages $count_pages";

?>

[/php]

Custom Counts

For complex counts you may need to use wpdb custom searches or mysql lookups.

This code will help you find the number of Categories on your site.

[php]

<?php

$numcats = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->categories");

?>

[/php]

Note

There are a number of plugins that can perform this work for you.

Check the NPSites Plugin Directory or The Extend area on wordpress.org