Have you ever wanted to display the total number of WordPress posts? How about displaying the total number of posts but excluding specific categories? You’ll learn both of these in this tutorial!
Display Total Number Of Posts
Let’s look at the code needed to count all the posts and display the total:
1 2 3 4 | <!--?php $total = wp_count_posts()--->publish; echo $total; ?> |
$total is the name of the variable I’m using. You can name it whatever you want. Then we use the wp_count_posts function to count all of the posts in Published status. Finally, we display the total count using the echo function.
Place the above code where you want the total to display. If you need to add text to it, you can use something like the following:
1 2 3 4 | <!--?php $total = wp_count_posts()--->publish; echo 'Total Posts: ' . $total; ?> |
Display Total Number Of Posts Excluding Categories
Now let’s look at the code needed to count posts while excluding specific categories and display the total.
1 2 3 4 5 6 7 | <!--?php $categories = get_categories('exclude=1,2,3'); foreach($categories as $category) { $total += $category--->count; } echo 'Total Posts: ' . $total; ?> |
$categories is the name of the variable I’m using. You can name it whatever you want. We then use the get_categories function and pass in the exclude argument listing the category ids we want to exclude.
Now that we have the categories we want to count, we count the number of posts for each category and total them. $total is the name of the variable I’m using. Again, name it whatever you want.
$total += $category->count could also have been written as $total = $total + $category->count.
Again, place the code where you want the total to display.
Read more about the WordPress wp_count_posts function as well as the WordPress get_categories function.