Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
calculate and display an estimated reading time
<?php
/**
* handle the calculation
* @param integer $seconds [description]
* @return [type] [description]
*/
function rkv_calc_read_time( $seconds = 0 ) {
// calc the minutes
$minutes = floor( $seconds / 60 );
// if the time is less than a minute, return that
if ( $minutes < 1 ) {
return __( 'less than 1 minute', 'rkv-reading-time' );
} else {
return sprintf( _n( '%d minute', '%d minutes', $minutes, 'rkv-reading-time'), $minutes );
}
}
<?php
/**
* display the estimated time to read the content
* @param [type] $content [description]
* @return [type] [description]
*/
function rkv_display_read_time( $content ) {
// fetch the global post object
global $post;
// check for our meta key
$seconds = get_post_meta( $post->ID, '_seconds_read_time', true );
// bail without the key
if ( empty( $seconds ) ) {
return $content;
}
// get our calculation
$readtime = rkv_calc_read_time( $seconds );
// create a prefix
$readprfx = __( 'Estimated read time:', 'rkv-reading-time' );
// make a fancy box
$readbox = '<p class="estimated-read-time"><strong>' . esc_attr( $readprfx ) . '</strong> ' . esc_attr( $readtime ) . '</p>';
// send it back before the content
return $readbox.$content;
}
add_filter( 'the_content', 'rkv_display_read_time', 10 );
<?php
/**
* store the estimated time to read the content
* @param integer $post_id [description]
* @return [type] [description]
*/
function rkv_store_read_time( $post_id = 0 ) {
// run various checks to make sure we aren't doing anything weird
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return $post_id;
}
// only save on posts. would probably set this to a filter
if ( get_post_type( $post_id ) != 'post' ) {
return $post_id;
}
// fetch the post content and get the word count
$content = get_post_field( 'post_content', $post_id, 'raw' );
$wordnum = str_word_count( strip_tags( $content ) );
// set the average reading time at 120 wpm
$avgtime = apply_filters( 'rkv_estimated_reading_time', 120 );
// calc the total seconds to read
$seconds = floor( (int) $wordnum / (int) $avgtime ) * 60;
// update the post meta
update_post_meta( $post_id, '_seconds_read_time', $seconds );
}
add_action( 'save_post', 'rkv_store_read_time' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.