25% off ProSNIPC25OFF

Estimated Reading Time Badge

Injects an estimated reading time badge just below the post title on single posts.

Module2 parts · by SnipCraft

PHPLogic

php
<?php
if ( ! function_exists( 'scseed_reading_time_badge' ) ) {
    function scseed_reading_time_badge( $content ) {
        if ( ! is_singular( 'post' ) || ! in_the_loop() || ! is_main_query() ) {
            return $content;
        }
        $word_count = str_word_count( wp_strip_all_tags( $content ) );
        $minutes    = max( 1, (int) ceil( $word_count / 200 ) );
        $label      = sprintf(
            _n( '%d min read', '%d min read', $minutes, 'scseed' ),
            $minutes
        );
        $badge = '<p class="scseed-read-time" aria-label="' .
                 esc_attr( sprintf( __( 'Estimated reading time: %d minutes', 'scseed' ), $minutes ) ) .
                 '"><span class="scseed-rt-icon">&#128336;</span> ' .
                 esc_html( $label ) . '</p>';
        return $badge . $content;
    }
    add_filter( 'the_content', 'scseed_reading_time_badge' );
}

CSSStyles

css
.scseed-read-time {
  display: inline-flex;
  align-items: center;
  gap: 0.4em;
  font-size: 0.82rem;
  color: #666;
  background: #f3f4f6;
  border-radius: 4px;
  padding: 0.25em 0.75em;
  margin-bottom: 1.25rem;
  font-style: normal;
}
.scseed-rt-icon {
  font-style: normal;
}
#frontend#ux#content#reading