The new blogging trend is letting your readers know how long a post will take them to read. You can easily add read time to a post using a plugin. But, there are just too many blog posts and tutorials out there that give you a plugin solution when you really need a PHP solution. Adding too many plugins to your site can slow it down and introduce security hazards. So, whenever possible, you should do your own coding or hire a developer for a longer-term solution.
If you’re looking for an all-in-one self-hosted solution, be sure to check out our WordPress hosting packages.
In this article, you will:
If you’re using a custom theme that was built for your site, this does not apply to your case.
A WordPress child theme lets you edit your current theme and save changes that won’t be overwritten when a theme update is released. If you are not using a child theme to make edits, you are best advised to follow the WordPress guidelines for creating child themes.
Basically, child themes are the safest way to edit your theme files and retain the changes you’ve made.
Once you’re sure that you can safely edit your theme files, you can easily do so using the WordPress theme editor. You will be editing the “Single Page” template, which controls only posts and not pages.
- Log into your WordPress Dashboard
- Select Theme Editor under Appearance
- Choose your theme’s single post template under Theme Files on the right side panel1
Now, any code you add to the single post theme template will affect all blog posts on your site.
Unless you are already familiar with PHP code, you’ll want to note that any code within PHP tags (
<?php ?>) will be evaluated differently than HTML. The code snippet provided here to estimate your post reading time must be placed outside of PHP tags.
Place this code in your template file wherever you want reading time to appear:
<?php $mycontent = $post->post_content; // wordpress users only $word = str_word_count(strip_tags($mycontent)); $m = floor($word / 200); $s = floor($word % 200 / (200 / 60)); $est = $m . ' minute' . ($m == 1 ? '' : 's') . ', ' . $s . ' second' . ($s == 1 ? '' : 's'); ?> <p>Estimated reading time: <?php echo $est; ?></p>
The above code snippet2 does all the calculation inside of PHP and then outputs the results in a basic HTML paragraph element. Feel free to update any of the settings, for example:
- Update the paragraph text by changing “Estimated reading time” to any text you prefer, or erase it entirely
- Change the estimated words per minute (200) to any value you think will be more appropriate for your readers
- If you’d rather not have a paragraph, change the HTML
<p>tags to fit your preference
And that’s all it takes to add real PHP reading time estimates to your site. No plugin required! Be sure to let us know if you have questions or comments.