Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add a Time to Read To Your WordPress Posts
<?php
function time_to_read( $content = false ) {
if ( is_single () ) {
// If content has not been passed in (via the filter), fetch it
if ( !$content ) { $content = get_the_content(); $add = false; } else { $add = true; }
// Get the cache, if the content was not provided and this is not a preview
$cache = false;
if ( !$add && !is_preview() ) { $cache = get_transient( 'time_to_read_' . get_the_id() ); }
// If cache was found, see if the post has updated. If so, trash it
if ( $cache ) { if ( isset( $cache[ 'updated' ] ) && $cache[ 'updated'] != get_the_modified_date() ) { $cache = false; } }
// If there is a cache, use it!
if ( $cache ) {
$content = $cache[ 'content'];
} else {
// Generate output
$time = str_word_count( strip_tags( $content ) ) / 300;
if ( $time == 0 ) { $time = 0.1; } // If there is no content, report < 1 minute
$rounded = ceil( $time );
$output = 'Time to read: ' . ( $time<1?'<':'' ) . $rounded . ' minute' . ( $rounded>1?'s':'' );
$generated = 'Code generated';
if ( $add ) { $content = $output . $content; } else { $content = $output; }
// Save cache, if content was not provided and this is not a preview
if ( !$add && !is_preview() ) {
$cache[ 'content' ] = $content;
$cache[ 'updated '] = get_the_modified_date();
set_transient( 'time_to_read_' . get_the_id(), $cache );;
}
}
}
return $content;
}
?>
@dartiss
Copy link
Author

dartiss commented Nov 14, 2017

Add this to your functions.php code and then following the instructions on the blog post below on how to integrate this onto your site - the end result is a lovely 'Time to Read' added to each post.

https://artiss.blog/2017/02/add-a-time-to-read-to-your-wordpress-posts/

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