WORDPRESS - Oxygen - toolset

Shortcode to display word count or reading time

Author: Aleš Sýkora, 1. 7. 2019

This shortcode &lsqbisword-count&rsqb 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 can be changed).

Usage of shortcode:

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]

Snipped Created By: Nigel Anderson

for Toolset Views