# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Developer](https://wpide.com/library/category/developer/)
- Tags: rest-api, reading-time, headless
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/rest-reading-time-field/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Word Count and Reading Time in the REST API" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
