wp_count_posts()
Gets the number of posts of any post type and any status (publish, draft).
This function provides an efficient method of finding the amount of post's type a blog has. Another method is to count the amount of items in get_posts(), but that method has a lot of overhead with doing so. Therefore, when developing for 2.5+, use this function instead.
The $perm parameter checks for 'readable' value and if the user can read private posts, it will display that for the user that is signed in.
Hooks from the function
Return
stdClass
. Number of posts for each status.
Usage
$counts = wp_count_posts( $type, $perm );
- $type(string)
- The name of the post type whose number of posts you want to count.
Default: 'post' - $perm(string)
- To add private posts of current authorized user to the counts, set this parameter to
readable
.
Default: ''
Examples
#1 Basic usage
Returns a data object about the number of posts of each status. You can use the var_dump() function to see what the object contains.
$count_posts = wp_count_posts(); // в итоге получим что-то такое: /* stdClass Object ( [publish] => 60 [future] => 0 [draft] => 9 [pending] => 3 [private] => 0 [trash] => 0 [auto-draft] => 3 [inherit] => 0 ) */
#2 Number of published posts
To get the number of published posts use this code:
$count_posts = wp_count_posts(); $published_posts = $count_posts->publish;
If you do not need PHP4 support, you can use such a shortened entry:
$published_posts = wp_count_posts()->publish;
#3 Consider drafts
To calculate how many drafts we have in the database use this code (for PHP5+):
$draft_posts = wp_count_posts()->draft;
#4 Consider other types of posts
To count how many published posts of custom post type we have, for example, new_post_type
, use this code:
$published_posts = wp_count_posts('new_post_type')->publish;
Notes
- Global. wpdb. $wpdb WordPress database abstraction object.
Changelog
Since 2.5.0 | Introduced. |