Block Bindings Source: Reading Time
Registers a "Reading time" block bindings source, so a Paragraph or Heading in your templates can show "5 min read" for the current post (WordPress 6.5+).
Opens WPIDE on
Code
// Average reading speed in words per minute.
$wpide_binding_wpm = 220;
add_action( 'init', function () use ( $wpide_binding_wpm ) {
if ( ! function_exists( 'register_block_bindings_source' ) ) {
return;
}
register_block_bindings_source( 'wpide/reading-time', array(
'label' => 'Reading time',
'uses_context' => array( 'postId' ),
'get_value_callback' => function ( $source_args, $block_instance ) use ( $wpide_binding_wpm ) {
$post_id = isset( $block_instance->context['postId'] ) ? (int) $block_instance->context['postId'] : get_the_ID();
$words = str_word_count( wp_strip_all_tags( (string) get_post_field( 'post_content', $post_id ) ) );
return esc_html( sprintf( '%d min read', max( 1, (int) ceil( $words / max( 1, $wpide_binding_wpm ) ) ) ) );
},
) );
} );
Notes
In the Code editor, add {"metadata":{"bindings":{"content":{"source":"wpide/reading-time"}}}} to a Paragraph block's attributes.
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.