Word Count and Reading Time in the REST API
Adds word_count and reading_time fields to posts in the REST API, so headless front ends and apps can show "5 min read" without counting words themselves.
Opens WPIDE on
Code
// Average reading speed.
$wpide_words_per_minute = 220;
// Post types that get the fields.
$wpide_reading_post_types = array( 'post', 'page' );
add_action( 'rest_api_init', function () use ( $wpide_words_per_minute, $wpide_reading_post_types ) {
$count = function ( $object ) {
$post = get_post( $object['id'] );
return $post ? str_word_count( wp_strip_all_tags( strip_shortcodes( $post->post_content ) ) ) : 0;
};
register_rest_field( $wpide_reading_post_types, 'word_count', array(
'get_callback' => $count,
'schema' => array( 'type' => 'integer', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true ),
) );
register_rest_field( $wpide_reading_post_types, 'reading_time', array(
'get_callback' => function ( $object ) use ( $count, $wpide_words_per_minute ) {
return max( 1, (int) ceil( $count( $object ) / max( 1, $wpide_words_per_minute ) ) );
},
'schema' => array( 'description' => 'Estimated reading time in minutes.', 'type' => 'integer', 'context' => array( 'view', 'edit', 'embed' ), 'readonly' => true ),
) );
} );
Notes
Change $wpide_words_per_minute to match your audience; add more post types to $wpide_reading_post_types.
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.