WordPress Post Counter! Display Number of Posts: Snippet or Code

This is quick guide on how to display the number of current posts (or pages) published on WordPress; either with a snippet for pages, posts & widgets or directly in the code with PHP — & without plugins of course.

This requires functions.php editing — or more like copy/pasting skills.

WordPress Post Count

Here are examples of basic snippets; just add the code to your functions.php and the snippet itself can be used in posts, pages and widgets.

Example 1: Total Number of Published Posts Snippet

function totalposts_function() {
$posts = wp_count_posts()->publish;
return $posts; }

add_shortcode('totalposts', 'totalposts_function');

Snippet “[totalposts]” test: Blogging hard at 298 posts to date!

Example 2: Total Number of Published Pages Snippet

function totalpages_function() {
$pages = wp_count_posts('page')->publish;
return $pages; }

add_shortcode('totalpages', 'totalpages_function');

Snippet “[totalpages]” test: This website has 6 pages in total.

Example 3: Number of Both Posts & Pages Snippet

function totalpostpage_function() {
$posts = wp_count_posts('post')->publish;
$pages = wp_count_posts('page')->publish;
return $posts + $pages; }

add_shortcode('totalpostpage', 'totalpostpage_function');

Snippet “[totalpostpage]” test: All posts and pages combined is 304.

Example 4: Number of posts in WordPress code

To add this directly to code; let’s say in your footer via footer.php so it shows on every single page of your WordPress website. Use the above code examples without the add_shortcode line if you don’t need the snippet feature.

Then add this line of PHP equipped with the function of your choice:

<?php echo totalposts_function(); ?>

For an example check out the footer of this page!

Few things to take note of:

If you want to use the snippet in html/text widgets you will also need to add these two lines to anywhere in your functions.php file:

add_filter( 'widget_text', 'shortcode_unautop' );
add_filter( 'widget_text', 'do_shortcode' );

Also you will want to use a WordPress child theme for this so the code is not over-written when you update your theme for example.

Thank you for stopping by and having a read.
Please share or mention this post if you found it beneficial.

Leave a Comment