Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save azeemhassni/80be6ef7776b5123babf323ac7355ce7 to your computer and use it in GitHub Desktop.
Save azeemhassni/80be6ef7776b5123babf323ac7355ce7 to your computer and use it in GitHub Desktop.
Add Estimated reading time to your WordPress blog posts
<?php
// functions.php
function get_reading_time($content, $words_per_minute = 300): int {
$striped = strip_tags($content);
$words = explode(' ', $striped);
return round(sizeof($words) / $words_per_minute);
}
add_filter('the_content', function($content){
if(!is_single()) {
return $content;
}
$reading_time = get_reading_time($content);
$reading_time_string = sprintf('~%d minute%s read', $reading_time, $reading_time !== 1 ? 's' : '' );
return "<div style='margin-bottom: 2rem;'>{$reading_time_string}</div>{$content}";
}, 100, 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment