How to Display the Number of Posts in WordPress

Home » Snippets » How to Display the Number of Posts in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Are you curious about how many posts you have on your WordPress website? Knowing the total number of posts can be useful for tracking your content production, analyzing user engagement, or simply keeping track of your website’s growth. In this article, we will explore different methods to display the number of posts on your WordPress site, ranging from manual coding to using plugins. Whether you’re an experienced developer or a beginner, you’ll find a method that suits your skill level and needs. Let’s dive in and discover how to easily showcase the number of posts on your WordPress website.

					function wpturbo_display_number_of_posts() {
    $count_posts = wp_count_posts();
    $published_posts = $count_posts->publish;
    echo "<p>Total number of posts: " . $published_posts . "</p>";
}
add_action( 'wp_footer', 'wpturbo_display_number_of_posts' );
				

The code snippet provided allows you to display the total number of published posts on your WordPress website. Let’s break down how this code works.

The wpturbo_display_number_of_posts() function is defined to handle the task of retrieving and displaying the post count. Inside the function, we use the wp_count_posts() function to get an object that contains the count of published, drafts, and other post types.

$count_posts = wp_count_posts();

Next, we access the publish property of the $count_posts object to get the count of published posts.

$published_posts = $count_posts->publish;

Now, we echo out the total number of posts inside a <p> tag using concatenation to include the count value.

echo "<p>Total number of posts: " . $published_posts . "</p>";

To ensure that this function runs at the appropriate time and place on the website, we use the add_action() function to hook the wpturbo_display_number_of_posts() function into the wp_footer action. This action is triggered right before the closing </body> tag of the webpage.

add_action( 'wp_footer', 'wpturbo_display_number_of_posts' );

This means that the total number of posts will be displayed at the bottom of every page on your WordPress website.

You can modify the placement of the post count by changing the hook in add_action() to a different action that suits your needs.

That’s it! Now, whenever a user visits your website, they will be able to see the total number of published posts at the specified location.

Register an account to save your snippets or go Pro to get more features.