Skip to content
Snippet Gutenbergphpwordpress php

How to Display Reading Time in WordPress

Learn how to calculate and display estimated WordPress post reading time with a lightweight PHP function and Gutenberg-friendly shortcode, without installing a dedicated reading-time plugin.

Updated

/**
 * Estimate reading time from the saved content of a WordPress post.
 *
 * @param int $post_id          Post ID; defaults to the current post.
 * @param int $words_per_minute Reading speed, default 200 WPM.
 * @return int Estimated minutes, or 0 for empty/invalid content.
 */
function wdg_get_reading_time_minutes( $post_id = 0, $words_per_minute = 200 ) {
    $post_id = $post_id ? absint( $post_id ) : get_the_ID();

    if ( ! $post_id ) {
        return 0;
    }

    $content = get_post_field( 'post_content', $post_id, 'raw' );

    if ( ! is_string( $content ) || '' === trim( $content ) ) {
        return 0;
    }

    // Remove block markup, shortcodes, and HTML before counting words.
    $text = excerpt_remove_blocks( $content );
    $text = strip_shortcodes( $text );
    $text = wp_strip_all_tags( $text );
    $text = html_entity_decode( $text, ENT_QUOTES | ENT_HTML5, 'UTF-8' );

    // Count words with Unicode support (including accented characters).
    $word_count = preg_match_all(
        "/[\\p{L}\\p{N}]+(?:['’\\-][\\p{L}\\p{N}]+)*/u",
        $text
    );

    if ( ! $word_count ) {
        return 0;
    }

    $speed = max( 1, absint( $words_per_minute ) );

    return (int) ceil( $word_count / $speed );
}

/**
 * Usage: [wdg_reading_time] or [wdg_reading_time wpm="250"]
 */
function wdg_reading_time_shortcode( $atts ) {
    $atts = shortcode_atts(
        array( 'wpm' => 200 ),
        (array) $atts,
        'wdg_reading_time'
    );

    $minutes = wdg_get_reading_time_minutes( get_the_ID(), $atts['wpm'] );

    if ( 0 === $minutes ) {
        return '';
    }

    $label = sprintf(
        /* translators: %s: estimated reading time in minutes. */
        __( '%s min read', 'your-text-domain' ),
        number_format_i18n( $minutes )
    );

    return '<span class="wdg-reading-time">' . esc_html( $label ) . '</span>';
}
add_shortcode( 'wdg_reading_time', 'wdg_reading_time_shortcode' );

This WordPress snippet adds a simple estimated reading time label to your posts without requiring a dedicated reading-time plugin. It counts the words in a post’s saved content, divides that number by an assumed reading speed and shows the result wherever you insert a shortcode.

Example output: 3 min read

The solution uses PHP and the WordPress Shortcode API. You can install it in a small custom plugin, a PHP-enabled code-snippets plugin or your child theme’s functions.php file. Your post content remains editable in Gutenberg.

  • Category: WordPress Snippets
  • Language: PHP
  • Level: Beginner
  • Estimated setup time: 5–10 minutes
  • What you will add: one PHP helper function and one shortcode, [wdg_reading_time]

1. What This Snippet Does

The code reads the current post’s stored content, removes block/shortcode/HTML markup for the purpose of estimating word count, and counts words using a Unicode-aware regular expression. It then divides the total by a configurable reading speed, rounds up to the next full minute, and returns a small HTML label.

For instance, at the default 200 words per minute, 450 words becomes ceil(450 / 200), or 3 min read. A post with no countable text produces no label.

This is an estimate, not an exact measurement of how long each visitor will need. The calculation is based on stored content rather than content generated later by dynamic blocks or JavaScript.

2. Before You Start

Make sure you have:

  1. A working WordPress site and permission to add PHP safely.
  2. A child theme, a small custom plugin, or a code-snippets plugin capable of running PHP. Avoid editing third-party parent theme files, because updates may overwrite your additions.
  3. A published or draft test post with some text, so you can check the result in Preview.
  4. Access to the WordPress Block Editor (Gutenberg) if you intend to use the shortcode in post content.

Important: Add the main code only once. If you place it in a PHP functions.php file that already begins with <?php, do not paste an additional opening PHP tag. Back up your site and test custom PHP safely before using it on production.

3. Complete PHP Code

Add the following code to your chosen PHP location. It defines the helper wdg_get_reading_time_minutes() and registers the [wdg_reading_time] shortcode. Keep the implementation together; do not duplicate the function definitions in multiple files.

The wdg_ prefix reduces the chance of colliding with other function and shortcode names. If you package the snippet for your own multilingual theme or plugin, replace your-text-domain with that project’s real text domain.

4. Add the Reading Time in Gutenberg

Once the PHP code is active on your own WordPress installation, open a post in the WordPress editor. Add a Shortcode block where you want the estimate to appear — for example, under the introduction or above the main body text.

Enter the following shortcode:

[wdg_reading_time]

Preview the post. If it has countable text, you should see an estimate such as 3 min read.

Change the Reading Speed

The shortcode assumes 200 words per minute by default. To calculate the estimate using 250 words per minute, use:

[wdg_reading_time wpm="250"]

The wpm attribute changes only the assumed reading speed. It does not alter the post content. The PHP helper makes sure the speed is at least 1, so an invalid or zero value cannot cause division by zero.

5. Alternative: Show Reading Time From a PHP Template

If you need the reading time directly inside a classic WordPress theme template such as single.php, you can call the same helper instead of placing a shortcode in the editor. Use this example inside the WordPress Loop, where get_the_ID() refers to the intended post:

$minutes = wdg_get_reading_time_minutes( get_the_ID() );

if ( $minutes > 0 ) {
    echo '<span class="wdg-reading-time">' . esc_html(
        sprintf(
            /* translators: %s: estimated reading time in minutes. */
            __( '%s min read', 'your-text-domain' ),
            number_format_i18n( $minutes )
        )
    ) . '</span>';
}

Do not install this as a second implementation. The template sample is an alternative way to display the output of the helper function already defined in Section 3. It does not register the function again.

The two approaches serve different use cases:

  • Shortcode: editors control placement per post from Gutenberg.
  • Template call: developers control placement automatically through a PHP template.

6. How the PHP Works

Identify the WordPress Post

wdg_get_reading_time_minutes( $post_id = 0, $words_per_minute = 200 ) accepts an optional post ID and reading speed. If no ID is provided, it uses get_the_ID() to identify the current post. absint() normalizes the numeric post ID. If there is no valid post ID, the helper returns 0.

Read Saved Post Content

get_post_field( 'post_content', $post_id, 'raw' ) retrieves the saved post body. The code checks that it is a nonempty string before continuing. The third argument requests the raw, unfiltered field value.

Remove Markup Before Counting

The calculation applies these functions in order:

  • excerpt_remove_blocks() is a WordPress Core function that processes Gutenberg blocks and retains content from block types suitable for excerpts. Some block types, including code blocks, may be excluded from the reading-time estimate. The following functions remove shortcodes and HTML tags from the retained content.
  • strip_shortcodes() removes shortcode syntax rather than counting shortcode tags as ordinary words.
  • wp_strip_all_tags() removes HTML tags.
  • html_entity_decode() converts encoded characters such as &amp; to their text equivalents.

This gives the code a cleaner text input than counting words directly in the saved HTML or block markup. It is not a full simulation of everything visible on the frontend: dynamic blocks, media and other generated content may behave differently.

Count Words With Unicode Support

The preg_match_all() expression searches for sequences of Unicode letters and numbers. It supports many accented characters and can keep common apostrophes or hyphens within a word. It is more language-tolerant than simply splitting text at ASCII spaces, but it is not an accurate universal word tokenizer for all languages.

If there are no matching words, the helper returns 0.

Convert Words Into Minutes

max( 1, absint( $words_per_minute ) ) ensures a positive divisor. ceil( $word_count / $speed ) always rounds up to a full minute; for example, at 200 WPM:

WordsEstimated reading time
1001 min
2001 min
4503 min
8004 min

These are arithmetic examples of the configured formula, not measurements of actual readers.

Create and Safely Return the Shortcode Label

shortcode_atts() merges the optional wpm setting with its default value. The shortcode calls the helper with the current post ID. A 0 result returns an empty string, while a positive result produces a localized label through __() and number_format_i18n().

Finally, esc_html() escapes the human-readable label, and the function returns the HTML <span class="wdg-reading-time">…</span> for WordPress to insert into the post output. add_shortcode() registers the shortcode name.

7. Test the Snippet on Your Own Site

After enabling the PHP in your own WordPress installation, check the following:

  1. Normal post: Add [wdg_reading_time] in a Shortcode block; confirm it displays a label in Preview.
  2. Custom speed: Try [wdg_reading_time wpm="250"]; the estimate may change depending on the word count.
  3. Short or long post: Confirm the label increases as the word count grows, using the rounded-up calculation.
  4. Empty post: Confirm the shortcode produces no label when the helper finds no countable text.
  5. Theme placement: If you use the optional PHP template call, verify it appears within the correct WordPress Loop.
  6. No duplicates: Confirm the PHP functions are loaded only once and the label is not printed twice by using both display methods unnecessarily.

The .wdg-reading-time CSS class provides a styling hook if your theme needs one, but no CSS is required for the basic text label. For this snippet, the output is deliberately simple.

8. Troubleshooting

The shortcode displays as literal text

Make sure the PHP code is actually loaded on the WordPress site where the shortcode is being used, and that add_shortcode( 'wdg_reading_time', ... ) has run. The shortcode can only execute in WordPress content when it has been registered. Use a real Shortcode block on the reader’s site; a Code block is meant to show the shortcode literally for documentation.

The result is empty

The helper returns 0 when there is no valid current post, no saved content, or no matching countable words. Check that the shortcode is used in a post context and that the post contains ordinary text.

The number feels inaccurate

The calculation assumes a fixed words-per-minute value and reads the stored content. Viewing images, watching video, interpreting code and loading dynamic block content are not added separately. Change the wpm value if a different estimate is more appropriate for your audience.

You get a PHP function-redeclaration error

Check that you have not pasted the complete code into both functions.php and a custom plugin. The main implementation should be registered once, not duplicated in multiple PHP locations.

9. Notes and Limitations

  • The default 200 WPM reading speed is an approximation; different readers and subjects require different amounts of time.
  • The helper counts saved WordPress post content, not text assembled at runtime by dynamic blocks, shortcodes or JavaScript.
  • Images, videos, interactive examples and code comprehension time are not added separately.
  • Unicode-aware word matching helps with accented text, but Chinese, Japanese and other scripts without conventional word separators need a language-appropriate word segmentation strategy for reliable reading estimates.
  • For maintainability, prefer a small custom plugin or a child theme rather than editing a third-party parent theme that will receive updates.
  • The provided snippet is educational and should be tested on the reader’s site; it is not installed or executed by viewing this Web Dev Guru page.

10. WordPress Documentation

Official WordPress references for the APIs used in this example:

Conclusion

You now have a lightweight way to display an estimated reading time for WordPress posts using PHP and a Gutenberg-friendly shortcode. The helper handles content cleanup, estimates minutes from a configurable reading speed and returns a simple label that you can place in a post or render from a classic PHP template.

Start with [wdg_reading_time] for the 200-WPM default, or use [wdg_reading_time wpm="250"] to change the estimate. The post body remains editable in WordPress and the shortcode controls only the displayed reading-time label.