Introduction
A reading time indicator is a helpful feature that gives your readers an idea of how long it will take to read an article. In this tutorial, we’ll show you how to add a simple reading time indicator to your WordPress posts using a custom code snippet in your theme’s functions.php file. This indicator will automatically calculate the reading time based on the number of words in your post and display it at the bottom of the article.
The Code Snippet
Here is the code snippet you need to place in your theme’s functions.php file:
function leestijd_weergeven_shortcode() {
$content = get_post_field('post_content', get_the_ID());
$woordenteller = str_word_count(strip_tags($content));
$leestijd_minuten = ceil($woordenteller / 200); // Gemiddeld leestempo is 200 woorden per minuut
if ($leestijd_minuten == 1) {
$leestijd = '1 minuut leestijd';
} else {
$leestijd = $leestijd_minuten . ' minuten leestijd';
}
return '<div class="leestijd">' . $leestijd . '</div>';
}
add_shortcode('leestijd_weergeven', 'leestijd_weergeven_shortcode');
Follow the steps below to add the code.
- Go to your WordPress dashboard: Log in to your WordPress dashboard using your username and password.
- Navigate to the Theme Editor: In the dashboard, click on “Appearance” and then on “Theme Editor.”
- Locate the
functions.php
file: On the right side of the screen, you’ll see a file namedfunctions.php
. Click on it to open it for editing. - Add the code: Scroll all the way to the bottom of the
functions.php
file. Paste the previously provided code snippet at the very end of the file. - Save the changes: Click the “Update File” button to save your changes.
Explanation of the Code
- In this code, we use the function
leestijd_weergeven()
to calculate the reading time of a post. - We retrieve the content of the post using
get_post_field()
. - Next, we count the number of words in the content and divide it by 200, which represents an average reading speed of 200 words per minute.
- We round the calculated reading time up to the nearest whole minute.
- Depending on the reading time, we display either “1 minute read” or “[number] minutes read” in an HTML div.
How to Use the Snippet within Elementor
- After placing and saving the code in the functions.php file, go to your WordPress dashboard.
- Click on “Posts” and open the post where you want the reading time indicator to appear.
- Edit the post with Elementor.
- Add a Text widget or any other widget where you want the reading time indicator to appear.
- Place the shortcode inside the widget.
- Update your post and preview it. You will now see the reading time indicator in your post.
Conclusion
Congratulations! You’ve successfully added a reading time indicator to your posts. This will help your readers estimate how long it will take to read your articles. You can place this shortcode wherever you like, but we recommend adding it to a single post template so you only need to insert it once.
Show us your result!