Aleš Sýkora / December 6, 2023 / 0 comments
Shortcode to display word count or reading time in Toolset Views
min read / WordPress / Share on: Twitter, LinkedIn, Facebook
Post summary: This shortcode “word-count” will display a count of words for whatever content is passed, and can optionally display an estimated reading time.
This shortcode [word-count]
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]
/*Reading time:*/ [word-count time=true pace=100][wpv-post-body view_template="None"][/word-count]
Fuel my passion for writing with a beer🍺
Your support not only makes me drunk but also greatly motivates me to continue creating content that helps. Cheers to more discoveries and shared success. 🍻