- S'abonner au fil RSS
- Marquer le sujet comme nouveau
- Marquer le sujet comme lu
- Placer ce Sujet en tête de liste pour l'utilisateur actuel
- Marquer
- S'abonner
- Page imprimable
How to Add Reading Minutes to Blog Posts
03-18-2017 12:03 - modifié 09-27-2019 09:43
I wanted to visually show my readers how long blog posts are in minutes. I felt that this would be a great way to keep my readers engaged. Plus it looks cool.
In my blog template, I edited the Post Template and Listing Template. I looked for the HubL loop section,
{% for content in contents %}
Inside this section is where the system will loop through how many posts I have published. I knew I wanted mine next to the post Date, Author, and Topics.
Here is the code I added using a simple HubL variable and filters.
{{ content.post_body|wordcount|divide(300) }}
The first part, content.post_body is getting all the information from the post body. Pretty straightforward. Then appending the filter |wordcount which is telling us to get the total number of words in the post_body. After that, I then added |divide(300). The average adult human reads 300 words per minute.
To finish up I added the span class to stylize with CSS and then added the appropriate font awesome tag.
<span class="reading-minutes"> {{ content.post_body|wordcount|divide(300) }} minute read </span>
You now have implemented the finished code like in my image above.
NOTE:
This code will always round down. I found that if I had 899 words and then divided it by 300 it would show me 2 and not 3. I have updated my code as follows for it to always round up or down to the nearest 100. I also added an If statement to check to see if the post-reading time is less than 1. Maybe you have a post with just one video or infographic and it would not look good with a 0 for the reading minutes.
Update: Added the striptag filter to the code below to remove any of the HTML from videos or images and such that could cause your final outcome to be extremely high when it comes to reading minutes.
<span class="reading-minutes"> {% set initialPostWords = content.post_body|striptags|wordcount %} {% set calculatedPostWords = (initialPostWords/100) * 100 %} {% set finishedPostWords = calculatedPostWords|divide(300)|round(2) %}
{% set number = finishedPostWords|round %}
{% if number < 1 %}
{% else %}
{{ finishedPostWords|round }} minute read
{% endif %} </span>
Let me know what you think.
- Marquer comme nouveau
- Marquer
- S'abonner
- S'abonner au fil RSS
- Surligner
- Imprimer
- Envoyer à un ami
- Signaler un contenu inapproprié