Add Snippet To Project
Do you ever find yourself curious about the length of your WordPress posts or articles? Knowing the word count can be helpful for various reasons, such as planning content or meeting specific requirements. In this article, we will show you how to display the word count of your WordPress posts or pages, making it easier to keep track of your writing progress and ensure your content meets your goals.
function wpturbo_display_word_count() {
// Get the post content
$post_content = get_post_field('post_content', get_the_ID());
// Count the number of words
$word_count = str_word_count(strip_tags($post_content));
// Output the word count
echo 'Word Count: ' . $word_count;
}
add_action('wp_footer', 'wpturbo_display_word_count');
The code snippet I provided demonstrates how to display the word count of a post in WordPress. Let’s break down how it works step by step.
First, we define a function called wpturbo_display_word_count()
. This function will be responsible for calculating and displaying the word count.
Inside the function, we retrieve the post content using the get_post_field()
function. We pass two parameters to the function: 'post_content'
, which specifies that we want to retrieve the content of the post, and get_the_ID()
, which retrieves the ID of the current post. This ensures that we are getting the content of the post that is being displayed.
Next, we use the str_word_count()
function to count the number of words. We pass the post content retrieved in the previous step to this function. The str_word_count()
function counts the number of words in a string and returns the count.
To ensure accurate word count, we use the strip_tags()
function to remove any HTML tags from the post content before counting the words. This ensures that we are only counting the plain text words and excluding any HTML markup.
After calculating the word count, we output it using the echo
statement. In this case, we display the word count with the text "Word Count: " appended to it.
Finally, we hook the wpturbo_display_word_count()
function to the wp_footer
action using the add_action()
function. This ensures that the word count will be displayed in the footer of every WordPress page.
By adding this code to your theme’s functions.php
file, the word count will be displayed on your WordPress site.