How to display total number of Custom Posts on a WordPress site

Based on this quick tip from WPRecipes, I was able to quickly figure out how to count and display the number of Custom Posts (of a particular type) that I had on a site.

[sourcecode language=”php”]
<?php
$numposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE (post_status = ‘publish’ AND post_type = ‘listing’)");
if (0 < $numposts) $numposts = number_format($numposts);
?>
[/sourcecode]

Simply replace post_type = 'listing' with whatever you’ve named your custom post type. Then, to get the number to display somewhere on your page, simply insert the following code where appropriate:

[sourcecode language=”php”]
<?php echo $numposts ?>
[/sourcecode]

3 Replies to “How to display total number of Custom Posts on a WordPress site”

  1. This code saved my butt today, thank you! I’m using it as a simple way to get the /page/ number to link to the last custom post I have without using permalinks.

  2. Thanks for posting this! It also saved my butt!!

    Would you know how to display the number of custom post types from a custom post type category?

Comments are closed.