Aleš Sýkora / December 6, 2023 / 0 comments
Display published post number in WordPress
min read / Custom Code, WordPress / Share on: Twitter, LinkedIn, Facebook
Post summary: To display a number of published posts you need a wp_count_posts php function.
In this tutorial, I will guide you through the simple process of displaying the count of posts on your WordPress website. This can be used within any builder or WP theme. Let’s dive in.
Step 1: Understanding the wp_count_posts
Function
You need to use the WordPress built-in function wp_count_posts
to efficiently count the number of posts. This function is preferred over other methods (get_posts, direct database query, post loop) for its efficiency and ease of use.
Step 2: Writing the Code
Add the following code to your code snippets plugin or to your child theme’s functions.php
file or to your custom functionality plugin or to your custom page template or whatever you damn want!
// This code snippet creates a function which fetch the count of published posts.
function great_tit_post_count() {
$count_posts = wp_count_posts();
$published_posts = $count_posts->publish; //get only published posts count
return $published_posts;
}
Then you can use echo to display the published post count:
echo 'Total number of published posts: ' . get_post_count();
Or if you use the Bricks Builder for example, you can use this in curly brackets:
echo:great_tit_post_count
Step 3: Customizing Post Types (CPT)
If you need to count custom post types, simply insert the CPT name as an argument to wp_count_posts
. Or you can use this enhanced function and pass the name of CPT when you call it.
function great_tit_cpt_post_count($post_type) {
$count_posts = wp_count_posts($post_type);
$published_posts = $count_posts->publish;
return $published_posts;
}
And then call the function:
echo 'Total number of published custom posts: ' . get_custom_post_count('your_cpt_slug');
Conclusion: With this quick and easy method, you can dynamically display the total number of posts or CPT’s on your WordPress site. This is a great way to keep your readers informed about the volume of your content and encourage them to explore more.
Additional Tips:
- Remember to back up your site before making changes to the code.
- Explore different places in your theme to display this count.
Fuel my passion for writing with a beer🍺
Your support not only makes me drunk but also greatly motivates me to continue creating content that helps. Cheers to more discoveries and shared success. 🍻