Halloween Sale 15% off Ends in See the plans
PHP

Bricks Dynamic Tag: {wpide_reading_time}

Adds a {wpide_reading_time} dynamic data tag that shows the estimated reading time of the current post ("5 min read"), for single templates and query loops.

Don’t have WPIDE yet? Install it on your site

Code

// Average reading speed in words per minute.
$wpide_bricks_wpm = 220;

$wpide_bricks_reading_time = function ( $post_id ) use ( $wpide_bricks_wpm ) {
    $words = str_word_count( wp_strip_all_tags( (string) get_post_field( 'post_content', $post_id ) ) );

    return sprintf( '%d min read', max( 1, (int) ceil( $words / max( 1, $wpide_bricks_wpm ) ) ) );
};

add_filter( 'bricks/dynamic_tags_list', function ( $tags ) {
    $tags[] = array( 'name' => '{wpide_reading_time}', 'label' => 'Reading time', 'group' => 'Post' );

    return $tags;
} );

add_filter( 'bricks/dynamic_data/render_tag', function ( $tag, $post = null, $context = 'text' ) use ( $wpide_bricks_reading_time ) {
    $name = is_string( $tag ) ? trim( $tag, '{}' ) : $tag;

    if ( 'wpide_reading_time' !== $name ) {
        return $tag;
    }

    return $wpide_bricks_reading_time( $post instanceof WP_Post ? $post->ID : get_the_ID() );
}, 20, 3 );

$wpide_bricks_reading_replace = function ( $content, $post = null ) use ( $wpide_bricks_reading_time ) {
    if ( ! is_string( $content ) || false === strpos( $content, '{wpide_reading_time}' ) ) {
        return $content;
    }

    return str_replace( '{wpide_reading_time}', $wpide_bricks_reading_time( $post instanceof WP_Post ? $post->ID : get_the_ID() ), $content );
};

add_filter( 'bricks/dynamic_data/render_content', $wpide_bricks_reading_replace, 20, 2 );
add_filter( 'bricks/frontend/render_data', $wpide_bricks_reading_replace, 20, 2 );

Notes

Change the words-per-minute value to match your audience.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.