Home / Admin / Estimated reading time
Duplicate Snippet

Embed Snippet on Your Site

Estimated reading time

Code Preview
php
<?php
// Estimated reading time
function readTime ( $content = '', $words_per_minute = 250, $with_gutenberg = false ) {
	// In case if content is build with gutenberg parse blocks
	if ( $with_gutenberg ) {
		$blocks = parse_blocks( $content );
		$contentHtml = '';
		foreach ( $blocks as $block ) {
			$contentHtml .= render_block( $block );
		}
		$content = $contentHtml;
	}
	// Remove HTML tags from string
	$content = wp_strip_all_tags( $content );
	// When content is empty return 0
	if ( !$content ) {
		return 0;
	}
	// Count words containing string
	$words_count = str_word_count( $content );
	// Calculate time for read all words and round
	$minutes = ceil( $words_count / $words_per_minute );
	return $minutes . ' min read';
}

Comments

Add a Comment