Unlock the Secret to Effortless Website Magic: Build Your First WordPress Plugin Today!
function qrt_add_reading_time( $content ) {
// Only on single posts in the main loop
if ( ! is_singular( 'post' ) || ! in_the_loop() || ! is_main_query() ) {
return $content;
}
// 1. Strip HTML/shortcodes, count words
$plain = wp_strip_all_tags( strip_shortcodes( get_post()->post_content ) );
$words = str_word_count( $plain );
// 2. Estimate: 200 words per minute
$minutes = max( 1, ceil( $words / 200 ) );
// 3. Build the badge
$badge = sprintf(
'<p class="qrt-badge" aria-label="%s"><span>%s</span></p>',
esc_attr__( 'Estimated reading time', 'quick-reading-time' ),
/* translators: %s = minutes */
esc_html( sprintf( _n( '%s min read', '%s mins read', $minutes, 'quick-reading-time' ), $minutes ) )
);
return $badge . $content;
}
add_filter( 'the_content', 'qrt_add_reading_time' );
This snippet adds a reading time badge to post content using the the_content
filter. It checks context with is_singular()
, in_the_loop()
, and is_main_query()
to ensure the badge only appears on single posts in the main loop.