Skip to content

Instantly share code, notes, and snippets.

@VincentVToscano
Last active October 20, 2020 16:31
Show Gist options
  • Select an option

  • Save VincentVToscano/5a862dbb752fbd26b71c7c5790e57cc1 to your computer and use it in GitHub Desktop.

Select an option

Save VincentVToscano/5a862dbb752fbd26b71c7c5790e57cc1 to your computer and use it in GitHub Desktop.
Get the estimated reading time of an article, blog post, or custom post in WordPress
<?php
/**
* get_estimated_reading_time --- Get estimated reading time in minutes
* @author Vincent V. Toscano
* Created by Vincent on Oct. 19, 2020
* Updated Oct. 20, 2020
* Ref.: get_the_content https://developer.wordpress.org/reference/functions/get_the_content/
* Ref.: strip_shortcodes https://developer.wordpress.org/reference/functions/strip_shortcodes/
* Ref.: strip_tags https://www.php.net/manual/en/function.strip-tags.php
* @param string $content Feed the method your copy/content/string
* @param int $wpm Typical/average words per minute 200 to 400 wpm
* @return false|float
* @example <?php $readTime = get_estimated_reading_time( get_the_content() ); ?>
* <time datetime="P<? echo $readTime?>M"><? echo $readTime?> minute<?php if ($readTime > 1)echo 's'; ?></time>
*/
function get_estimated_reading_time( $content = '', $wpm = 250 ) {
$cleaned_content = strip_tags( strip_shortcodes( $content ) );
$word_count = str_word_count( $cleaned_content );
$time = ceil( $word_count / $wpm );
return $time;
}
@VincentVToscano
Copy link
Copy Markdown
Author

Initial function with examples

Used to estimate the reading time based on length of article or post and the chosen words per minute param.

@VincentVToscano
Copy link
Copy Markdown
Author

Updated comment and example to use echo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment