Post reading time shortcode

Davor Mlinarić
16 May 2022

This snipet create a shortcode that you can use on any post to show estimated reading time in minutes. It will simply return a number of minutes.

Shorcode: [reading_time] or [reading_time wpm="100" gt="true"]

function wb_reading_time( $atts ) {
    
    $atts = shortcode_atts(array('wpm' => '300','gt' => 'false',),  $atts,'reading_time');
    return estimate_reading_time_in_minutes($atts['wpm'], esc_html( $atts['gt'] ));

}
add_shortcode( 'reading_time', 'wb_reading_time' );

function estimate_reading_time_in_minutes ($words_per_minute = 300, $with_gutenberg = false ) {
   
    global $post;
    $content = apply_filters('the_content',$post->post_content);

    if ( $with_gutenberg ) {
        $blocks = parse_blocks( $content );
        $contentHtml = '';

        foreach ( $blocks as $block ) {
            $contentHtml .= render_block( $block );
        }

        $content = $contentHtml;
    }
            
    $content = wp_strip_all_tags( $content );
           
    if ( !$content ) {return 0;}
            
    $words_count = str_word_count( $content );
    $minutes = ceil( $words_count / $words_per_minute );
            
    return $minutes;
}

Was this article helpful?

Tags

Categories

Never miss new post again

Subscribe and get list of new posts in your inbox

Click to Copy