Shortcode to display word count or reading time

Register a shortcode ‘word-count’ that will display a count of words for whatever content is passed, and can optionally display an estimated reading time.

/**
 * Register word-count shortcode
 */
add_shortcode('word-count', function ($atts = [], $content = null) {

	// Defaults
    $atts = shortcode_atts(
        array(
			'time' => false,
			'pace'	=> 150
        ),
        $atts
    );

	if ( isset( $content ) ){
		$content = apply_filters( 'the_content', $content );
		$content = wp_strip_all_tags( $content );
		$word_count = count( preg_split( '/s+/', $content ) );
		$reading_time = ceil( $word_count / $atts['pace'] );

		return ( $atts['time' ] ) ? $reading_time : $word_count;
	}
});

Use on its own to output word count, e.g. in a template to output the word count of the post content, or pass ‘time’ and optional ‘pace’ parameters to output estimated reading time (pace defaults to 150 words per minute).

Word count: [word-count][wpv-post-body view_template="None"][/word-count]

Read time: [word-count time=true pace=100][wpv-post-body view_template="None"][/word-count]


Let us know if this snippet is not working for you:

This snippet doesn’t work
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments