How to display the number of posts in WordPress

How to show the number of posts in WordPress

You can display the number of posts published  (excluding pages) with the following function:

<?php
$count_posts = wp_count_posts();
$published_posts = $count_posts->publish;
?>

If you intend to use PHP5 only, the following code is also available:

<?php
$published_posts = wp_count_posts()->publish;
?>

Please refer to this WordPress Codex page를 for more about wp_count_posts().

How to show the number of posts of the current category

If you want to display the total number of posts in the current category in the category.php file or other archive file, please use the folloiwng function:

function display_current_category_post_count() {
$count = '';
if(is_category()) {
global $wp_query;
$cat_ID = get_query_var('cat');
$categories = get_the_category();
foreach($categories as $cat) {
$id = $cat->cat_ID;
if($id == $cat_ID) {
$count = $cat->category_count;
}
}
}
return $count;
}
(Source: http://gabrieleromanato.name/)

 

To display the number of posts within a specific category:

get_category(CATEGORY_ID)->count;

(Please replace "CATEGORY_ID" with the corresponding category ID number.)


Leave a Comment