How to create Gutenberg reading time block

In this tutorial, we are going to create a reading time block for Gutenberg. By the end of this tutorial, you’ll have a working reading time block.

The benefits of adding the estimated reading time in an article are that the reader can prioritize what they want to read, can assess the difficulty of the text, can easily gauge how long the text is, and it gives people an idea of how long it will take to read the piece.

Pre-requisites

Here are some recommended pre-requisites for you:

  1. Already Scaffolded Block: You need an already scaffolded Gutenberg block, You can follow our How to Create Custom Gutenberg Block for WordPress – The Beginners Guide for creating a new Gutenberg block.

What are we going to create?

In my opinion, It’s very crucial to know what the end result will achieve before following a tutorial. Here’s what our final reading time block will look like:

reading time preview

Getting Started

Now that we’ve covered all the pre-requisites and introduction. You can now head over to your code editor and follow along with us.

The formula for calculating the reading time of an article

The main formula that we’re going to use for calculating the estimated reading time for particular text content.

For calculating the reading time, we need the following data of a particular content/article:

  1. Word Count (WC): Total words used in an article.
  2. Words Per Minute (WPM): This will be a constant value that contains the total number of words an average human can read in a minute. For the sake of this article, we are using “255” as the average words per minute.

Now here’s how you can calculate the estimated read time:

Math.ceil(Word Count / Words Per Minute) = Total Reading Time

Or

Math.ceil(WC / WPM) = Total Reading Time

Working for the editor

Adding reading in the editor interface is quite straightforward. Here’s the code responsible for displaying reading time in the Gutenberg editor. In the code below, we are just simply extracting the edited post content and displaying the estimated reading time by applying the formula above.

// src/edit.js
import { __, sprintf } from '@wordpress/i18n';

import { useSelect } from '@wordpress/data';
import { count as wordCount } from '@wordpress/wordcount';
import { useBlockProps } from '@wordpress/block-editor';

import './editor.scss';

export default function Edit() {

	const getCalculatedReadingTime = (content) => {
		// words per min for average adult.
		const WORDS_PER_MIN = 255;
		const totalWords = wordCount(content, 'words');
		const time = Math.ceil(totalWords / WORDS_PER_MIN);

		return time;
	}

	const readingTime = useSelect((select) => {
		const postContent = select('core/editor').getEditedPostAttribute('content');
		return getCalculatedReadingTime(postContent);
	});

	return (
		<p {...useBlockProps()}>
			{
				sprintf('The average reading time for this post is: %s min(s)', readingTime)
			}
		</p>
	);
}

Working for the frontend

Adding a reading time for the front won’t be as straightforward. We’re going to combine the client-side save content with the server-side computation. I think we can call this a hybrid gutenberg block between the client and server sides.

// src/save.js
import { __ } from '@wordpress/i18n';

import { useBlockProps } from '@wordpress/block-editor';

export default function save() {
	return (
		<p {...useBlockProps.save()}>
			The average reading time for this post is: %time% min(s)
		</p>
	);
}

Now let’s replace the "%time% with an actual reading time of the current post. We can achieve this computation with server-side implementation.

// main block php file
register_block_type( __DIR__ . '/build', [
		'render_callback' => function( $attributes, $content ) {
			global $post;
			
			$post_content = wp_strip_all_tags( $post->post_content );
			$words_per_min = 255;
			$total_words = str_word_count( $post_content );
			$time = ceil( $total_words / $words_per_min );

			return  str_replace( "%time%", $time, $content );
		}
] );

Wrapping Up

Let’s wrap up this tutorial here. Please comment below if you have any queries regarding this tutorial. Here are some quick tasks for you to improve your Gutenberg skills:

  1. Try adding some styling options for the reading time block
  2. Also, try adding estimated seconds to the total reading time.

💌

Unlock Exclusive Perks: Join Our VIP Subscriber Club Today!

Subscribe for special promotions, offers, freebies, and the latest updates and news – all exclusively for our VIPs. Don’t miss out, join now! 🌟💌🎁

We won’t send you spam, we promise.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Join the All Access Club

Your All-Inclusive Pass to Premium WordPress Products.