Reading Time in Feed Items
Shows an estimated reading time such as "4 min read" at the start of each item in your feeds, so subscribers know how long an article takes before they open it.
Opens WPIDE on
Code
// Average reading speed in words per minute.
$wpide_feed_wpm = 220;
// Label; %d is replaced by the minutes.
$wpide_feed_reading_label = '%d min read';
$wpide_feed_minutes = function () use ( $wpide_feed_wpm ) {
static $cache = array();
$post_id = get_the_ID();
if ( ! $post_id ) {
return 0;
}
if ( ! isset( $cache[ $post_id ] ) ) {
$text = wp_strip_all_tags( strip_shortcodes( (string) get_post_field( 'post_content', $post_id ) ) );
$words = preg_split( '/\s+/u', trim( $text ), -1, PREG_SPLIT_NO_EMPTY );
$cache[ $post_id ] = $words ? max( 1, (int) ceil( count( $words ) / max( 1, (int) $wpide_feed_wpm ) ) ) : 0;
}
return $cache[ $post_id ];
};
add_filter( 'the_excerpt_rss', function ( $excerpt ) use ( $wpide_feed_minutes, $wpide_feed_reading_label ) {
$minutes = $wpide_feed_minutes();
return $minutes ? esc_html( sprintf( $wpide_feed_reading_label, $minutes ) ) . ' · ' . $excerpt : $excerpt;
} );
add_filter( 'the_content_feed', function ( $content ) use ( $wpide_feed_minutes, $wpide_feed_reading_label ) {
$minutes = $wpide_feed_minutes();
return $minutes ? '<p><em>' . esc_html( sprintf( $wpide_feed_reading_label, $minutes ) ) . '</em></p>' . $content : $content;
} );
Notes
Change the words-per-minute value to match your audience; shortcodes and HTML are left out of the word count.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.