Estimate Reading Time

Estimated reading time: 1 minute(s)

Estimation of reading time of a post is a really helpful feature. In this article, we’ll show you a custom PHP function which you can add that to the source code of your Bricks childe function.php

/**
* Estimated reading time in minutes
* 
* @param $content
* @param $words_per_minute
* @param $with_gutenberg
* 
* @return int estimated time in minutes
*/

function estimate_reading_time_in_minutes ( $content = '', $words_per_minute = 300, $with_gutenberg = false ) {
    // In case if content is build with gutenberg parse blocks
    if ( $with_gutenberg ) {
        $blocks = parse_blocks( $content );
        $contentHtml = '';

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

        $content = $contentHtml;
    }
            
    // Remove HTML tags from string
    $content = wp_strip_all_tags( $content );
            
    // When content is empty return 0
    if ( !$content ) {
        return 0;
    }
            
    // Count words containing string
    $words_count = str_word_count( $content );
            
    // Calculate time for read all words and round
    $minutes = ceil( $words_count / $words_per_minute );
            
    return $minutes;
}

If you want to use with shortcode, Add this code under above code snippet.

function estimate_reading_time_shortcode( $atts ) {
    // Extract shortcode attributes
    $atts = shortcode_atts( array(
        'words_per_minute' => 300,
        'with_gutenberg' => false,
    ), $atts );

    // Get post content
    $content = get_post_field( 'post_content', get_the_ID() );

    // Call the estimate_reading_time_in_minutes function
    $reading_time = estimate_reading_time_in_minutes( $content, $atts['words_per_minute'], $atts['with_gutenberg'] );

    // Return the estimated reading time
    return '<p>Estimated reading time: ' . $reading_time . ' minute(s)</p>';
}
add_shortcode( 'reading_time', 'estimate_reading_time_shortcode' );

Source : acclaim, ChatGPT

Leave comment or code correction