If you need a count of all your posts in WordPress, there’s a pretty handy function called wp_count_posts() for that.

For example, if you have a post-type of ‘characters’ and you wanted to show a count of that, you can do this:

$to_count = wp_count_posts( 'characters' );
printf( __('Total Characters: %s'), $count->publish );

And that’s all well and good, but I was working on some SEO thoughts. In doing so, I ran into the recommendation that, for a ‘company’ type page, having a list of your posts was a bad idea. This made sense. After all, a site that is about non-traditional blog content shouldn’t start with a blog.

To correct this, I restructured the front page to show, in order:

  1. An introduction to the site
  2. The 4 newest characters added
  3. The 4 newest shows added
  4. The latest 10 blog posts

This keeps the blog information visible (which helps show that content is being updated) but also doesn’t drop people into a cold open. They can understand why they’re on the site, what they’re getting, and where to go.

But part of telling people about the site meant I wanted to indicate the depth of information. When I used to run a MediaWiki site, I used {{NUMBEROFARTICLES}} to list the number of articles. It was a very obvious way to display activity and attentiveness. If a site had 500 articles, it was probably getting up there. If it had 1500, it probably knew what it was doing.

That meant with WordPress what I wanted was a dynamic way to show the number of posts in a post type, like [numberofposts type="characters"] with the default being posts.

The Code

function numberofposts_shortcode( $atts ) {
	$attr = shortcode_atts( array(
		'type' => 'post',
	), $atts );

	$posttype = sanitize_text_field( $attr['type'] );
	if ( post_type_exists( $posttype ) !== true ) $posttype = 'post';

	$to_count = wp_count_posts( $posttype );

	return $to_count->publish;

}
add_shortcode( 'numberofposts', 'numberofposts_shortcode' );

What I chose to do here was check if the post type exists and, if not, force it to show posts. That way there will never be an error, though it may not show you what you expected if you put in ‘posts’ as your post type.

Reader Interactions

%d bloggers like this: