How to Display the Word Count of a Post in WordPress

Home » Snippets » How to Display the Word Count of a Post 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 the length of your WordPress posts? Being aware of your word count is crucial for SEO purposes, for readability, or even just for your own record keeping. In this article, we will guide you through the process of displaying the word count for each of your WordPress posts. Whether you’re a beginner or a seasoned WordPress user, our simple step-by-step process will make this task easy and straightforward for you.

					function wpturbo_post_word_count($post_id){
    $content = get_post_field( 'post_content', $post_id );
    $word_count = str_word_count( strip_tags( $content ) );
    return $word_count;
}
echo wpturbo_post_word_count( get_the_ID() );
				

The code begins by defining a new function named wpturbo_post_word_count(). This function takes one parameter, $post_id, which you should replace with the ID of the post or page you want to count the words of.

Let’s decipher the function from inside-out:

The first line inside the function uses WordPress’s inbuilt function get_post_field(). This function fetches the data we need from the WordPress database, based on the parameters we passed into it. In this instance, we’re telling WordPress to get the 'post_content' field for the post or page with the ID $post_id.

$content = get_post_field( 'post_content', $post_id );

Next, we need to count the words in the $content. But before we do this, we need to ensure we’re not counting any HTML tags that might be in the content. We achieve this by passing the $content through the strip_tags() function, which will remove any HTML tags from the $content.

$word_count = str_word_count( strip_tags( $content ) );

The str_word_count() function then counts the number of words in the stripped content, and the result is stored in the $word_count variable.

The function then returns the $word_count, and when called it will provide the number of words in the post whose ID was passed as an argument in the function.

In the final line of the code snippet, the echo command prints the result of this function:

echo wpturbo_post_word_count( get_the_ID() );

Here, we’re calling our custom function and passing in get_the_ID() as the argument, which is a WordPress function that returns the ID of the current post or page. The effect of this is that, wherever this line of code is placed within the WordPress Loop on a template file, it will output the word count of the current post or page.

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