Reading Time Shortcode
Registers a [reading_time] shortcode that shows an estimated reading time such as "4 min read" for the current post.
Opens WPIDE on
Code
add_shortcode( 'reading_time', function ( $atts ) {
$atts = shortcode_atts( array(
'wpm' => 220,
'label' => 'min read',
), $atts, 'reading_time' );
$post = get_post();
if ( ! $post ) {
return '';
}
$words = str_word_count( wp_strip_all_tags( strip_shortcodes( $post->post_content ) ) );
$minutes = max( 1, (int) ceil( $words / max( 1, (int) $atts['wpm'] ) ) );
return '<span class="reading-time">' . esc_html( $minutes . ' ' . $atts['label'] ) . '</span>';
} );
Notes
Usage: [reading_time] or [reading_time wpm="250" label="minutes"].
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.