Halloween Sale 15% off Ends in See the plans
PHP

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.

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

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

  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.