Post Reading Time

Calculates and displays via shortcode the reading time of blog articles.

PHP
/**
 * Snippet Name:     Post Reading Time
 * Snippet Author:   coding-bunny.com
 * Description:      Calculates and displays via shortcode the reading time of blog articles.
 */
 
if ( ! function_exists( 'post_reading_time' ) ) {

    function post_reading_time( $content = null, $words_per_minute = 200, $display_label = 'Reading time: %d min' ) {
        if ( is_null( $content ) ) {
            global $post;
            if ( ! isset( $post ) ) return '';
            $content = get_post_field( 'post_content', $post->ID );
        }
        $word_count = str_word_count( wp_strip_all_tags( $content ) );
        $minutes = max( 1, ceil( $word_count / $words_per_minute ) );
        $label = sprintf( $display_label, $minutes );
        return '<span class="prt-reading-time">' . esc_html( $label ) . '</span>';
    }
}

if ( ! shortcode_exists( 'post_reading_time' ) ) {
    add_shortcode( 'post_reading_time', function() {
        return post_reading_time();
    });
}

How To Implement This Solution?

Leave a Reply