Description
This function first appeared in WordPress 2.5. It returns an object whose properties represent the number of posts in each post status for a given post type. We can also use wp_count_posts() as a template tag. The second argument controls whether private post statuses should be included. By default, if the user is not logged in, the count for private posts is not included in the returned object.
The function returns an object whose properties are the various post statuses. We can use PHP’s isset() function to check whether a given property exists, because not every post status will necessarily be present in the result.
Usage
<?php wp_count_posts( $type, $perm ); ?>
Parameters
$type
(string) (optional) The post type to count.
Default: 'post'
$perm
(string) (optional) Include private posts readable by the current user by setting this to 'readable'.
Default: empty string
Examples
Default usage
By default, the function returns an object containing the count of published posts and other available statuses. Since the return value is an object, we can inspect it with var_dump() while debugging.
$count_posts = wp_count_posts();
Get the number of published posts
To retrieve the number of published posts, call wp_count_posts() and then access the publish property.
$count_posts = wp_count_posts();
$published_posts = $count_posts->publish;
If you need backward compatibility with PHP 4, you must use the two-step form above. If you only support PHP 5, you can shorten it like this:
$published_posts = wp_count_posts()->publish;
Count drafts
Counting drafts works the same way as counting published posts.
$count_posts = wp_count_posts();
$draft_posts = $count_posts->draft;
Count pages
Counting pages is also done in the same way.
$count_pages = wp_count_posts('page');
Other uses
wp_count_posts() can be used to count entries of any post type in any status, including attachments and custom post types that may be added later.
