Skip to content

Instantly share code, notes, and snippets.

@dartiss
Created November 14, 2017 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dartiss/32d6d32c5f48058dcedc75ad7d3978b0 to your computer and use it in GitHub Desktop.
Save dartiss/32d6d32c5f48058dcedc75ad7d3978b0 to your computer and use it in GitHub Desktop.
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