Created
March 8, 2022 13:55
-
-
Save azeemhassni/80be6ef7776b5123babf323ac7355ce7 to your computer and use it in GitHub Desktop.
Add Estimated reading time to your WordPress blog posts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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