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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.