Site logo

Archived topic

Add minutes to read in Block Element – Post Meta Template

5 replies · Started by Dong on November 7, 2021

Viewing posts 1–6 of 6

Hi guys,

I just switched to using the Block Element for post meta and can't figure out how to add "minutes to read" to the meta. Previously, I used the default meta, and that worked fine. It's still working in my archive pages, like here:

https://dongknows.com/how-to/

But in a single post, it's not shown, like in this one:

https://dongknows.com/tesla-model-y-ev-and-that-range-anxiety/

I'm using the latest versions of the themes.

Please advise! Thanks!

-Dong.

Hi Dong,

It's likely not showing on single post page because of condition specificity.

Can you share the code you're using to add the read time? (if you're adding it using a hook element or block element, can you share the display rule location?)

Let us know.

Rule location is under post title, all posts.

Code:


function tu_estimated_reading_time() {
    $post = get_post();
    $content = $post->post_content;
    $wpm = 250; // How many words per minute.

    $clean_content = strip_shortcodes( $content );
    $clean_content = strip_tags( $clean_content );
    $word_count = str_word_count( $clean_content );
    $time = ceil( $word_count / $wpm );

    return $time . '-min';
}

add_filter( 'generate_post_date_output', function( $output ) {
    $output .= '<div class="read-time"> • ' . tu_estimated_reading_time() . ' Read</div>';

    return $output;
} );

Thanks

Ah I see now.

Your single post page is using a Block Element - Post meta so the same filter isn't applying to it.

But I think we can just convert the function to a shortcode so you can add a shortcode block to the post meta layout on your Block element template.

add_shortcode( 'show_reading_time', function() {
    ob_start();  
    $post = get_post();
    $content = $post->post_content;
    $wpm = 250; // How many words per minute.

    $clean_content = strip_shortcodes( $content );
    $clean_content = strip_tags( $clean_content );
    $word_count = str_word_count( $clean_content );
    $time = ceil( $word_count / $wpm );
    $display_time = $time . '-min';

    echo '<div class="read-time"> • ' . $display_time . ' Read</div>';
  
    return ob_get_clean();
} );

With this, you can use [show_reading_time] shortcode on your Block Element template layout. :D

That worked. Thanks, Elvin.

No problem. Glad to be of any help. :D

This archived topic is closed to new replies.