Show Published Post/Page Count inside WordPress Content

This is how you can show an automatically updating, published post or page count number anywhere on your WordPress blog or website. As shown below — I’m using a post sticked to my homepage with statistics about the site.

Total Blog Posts Published

Basically all that’s required is to place a snippet of code in PHP to the desired location on your website. To which there are a few possibilities — of which Insert PHP plugin by Will Bontrager Software, LLC, will probably be the easiest option to place the code anywhere inside a post or page. Alternatively, let’s say if you want to display the post count in the footer of every page — you could directly edit a child theme’s footer.php file and place the code there.

The plugin will allow you to put any PHP code inside square brackets like so:

Insert PHP

This shortcode represents the php opening “<?php” and closing “?>” tags.

The PHP5 Method (recommended):

This is the code to show number of published posts and put it in a sentence.

$total = wp_count_posts()->publish;
echo ‘Total blog posts published: ‘ . $total . ‘ <i>;

You can also specify the type to page or post by replacing the first line with:

$total = wp_count_posts( $post_type = ‘page’ )->publish;
$total = wp_count_posts( $post_type = ‘post’ )->publish;

The Old Method

You can try this code if you have browser compatibility issues

if ( $count_posts ) { $published_posts = $count_posts->publish; }
echo ‘Total blog posts published: ‘ . $count_posts . ‘ <i>;

Troubleshooting

WYSIWYG html editors, such as ‘TinyMCE Advanced‘ will convert the greater than “>” sign (also known as ‘close angled bracket’) into it’s “HTML Name” which is ‘&gt;‘. This will prevent the code from working, and you will get a blank or partial page.

Turning debug on the error message is something like:

[UTC] PHP Parse error: syntax error, unexpected ‘&’ in /home/user/public_html/wp-content/plugins/insert-php/insert_php.php(48) : eval()’d code on line 2

Just make sure the code stays intact by directly using the Text editor.

 

PS. Although Insert PHP hasn’t been updated for more than a year — it’s still working well on the latest versions of WordPress. Currently 4.6.1 — despite someone having marked it as broken on the plugin page.

Also there are surely other alternative plugins available if interested, this is just the one I found simple and easy to use.

 

I would appreciate it if you leave your website URL in the comments to show what you’ve done with this code. Thanks!

Leave a Comment