How to Get the total number of Posts in WordPress

In a recent project, I was looking to find out how many posts were in a Feedback custom post type, to display on a Dashboard widget similar to the “Right Now” Dashboard Widget that comes with WordPress.

I noticed that the only way to get a count of posts within a certain post type was using:

wp_count_posts( 'my_post_type' );

wp_count_posts() returns an object, which gives detailed information of each post status and how many posts were within that status. If you are using default post statuses, you can probably get away with this:

$num_posts = wp_count_posts('my_post_type', 'readable');
$total_count = $num_posts->published;


In my situation, we created custom post statuses for Feedback ( New, Resolved, etc. ), and wanted a total count of all Feedback submitted. Here is the solution:

$total_count = array_sum((array)wp_count_posts( 'my_post_type' ) );

Cast the object returned by wp_count_posts() to an array, and use PHP’s array_sum() function to add the values together.

if you want to exclude only a few post statuses, use this:

$num_posts = wp_count_posts('my_post_type', 'readable');
$num_posts = (array)$num_posts;
unset( $num_posts['draft'], $num_posts['private'] );

$total_count = array_sum( $num_posts );

Whereas if you want to only include a few statuses for your total count, it’s best to just type it out!

$num_posts = wp_count_posts('my_post_type', 'readable');

$total_count = num_posts->published + num_posts->draft;

Leave a Reply

Your email address will not be published. Required fields are marked *