×
  • Shared Hosting

    Fast reliable and affordable cPanel Web Hosting from $2.99 per month.

  • Reseller Hosting

    Multiple websites? No problem with our multi-site hosting package. From $5.99 per month.

  • Annual Hosting

    Save money on web hosting by paying annually. Starting at $29.99 per year.

  • VPS Servers

    Need more power and resources? Choose our VPS server, only $7.99 per month.

  • FREE HOSTING PLAN

    Ideal for students and unemployed.

    Register

PHP word count script for WordPress – Display the word count of a WordPress Article

08/12/2022 | |0 comment

If you are looking for a way to include the word count of a WordPress article or page for your readers and visitors, then this is for you. This script works by using some of WordPress’s built-in functions by getting the post content using the get_post_field function.

It then uses the strip_shortcodes and strip_tags functions to remove any shortcodes and HTML tags from the content, respectively. Finally, it uses the str_word_count function to count the number of words in the content and then displays the word count.

 

<?php

// Get the post content
$content = get_post_field('post_content', $post->ID);

// Strip shortcodes from the content
$content = strip_shortcodes($content);

// Strip tags from the content
$content = strip_tags($content);

// Count the number of words in the content
$word_count = str_word_count($content);

// Display the word count
echo $word_count;

?>

To use this PHP word count script for WordPress, you can add the code manually using your favorite code editor. Or via the WordPress  theme editor.

Here are the steps you can follow:

1, Log in to your WordPress website and go to the Dashboard.
2, In the Dashboard, go to Appearance > Editor. This will open the WordPress theme editor.
3, In the theme editor, select the theme that you want to edit from the drop-down menu in the upper-right corner of the page.
4, On the right side of the page, you will see a list of files associated with the selected theme. Look for the file where you want to add the script, generally the single.php file for single posts or the page.php file for pages.
5, Click on the file to open it in the editor.
6, Add the PHP script to the file where you want to display the word count. For example, you can add it right after the post content, like this:

Once you have added the script to your desired location, click the Update File button to save your changes.

After you have added the script to your WordPress website, the word count will be displayed on the pages or posts where you added the script. Keep in mind that you may need to customize the script to fit your specific needs and to match the design of your website.

Thank you for reading. Join our community forums for lots more tutorials and guides just like this one.

Chris

Freelance Technical SEO with - https://sitebee.co.uk