Display Post Word Count Shortcode
Shortcode [word_count] displays the total word count of the current or any specified post.
PHPby SnipCraft
php
<?php
/**
* Usage: [word_count]
* Optional: [word_count post_id="42"]
* Returns the plain integer word count of the post body.
*/
add_shortcode( 'word_count', 'scseed_word_count_shortcode' );
function scseed_word_count_shortcode( $atts ) {
$atts = shortcode_atts(
array( 'post_id' => 0 ),
$atts,
'word_count'
);
$post_id = $atts['post_id'] ? absint( $atts['post_id'] ) : get_the_ID();
if ( ! $post_id ) {
return '0';
}
$content = get_post_field( 'post_content', $post_id );
$content = strip_shortcodes( $content );
$content = wp_strip_all_tags( $content );
$words = preg_split( '/\s+/', trim( $content ), -1, PREG_SPLIT_NO_EMPTY );
return (string) count( (array) $words );
}#display#post#shortcode#statistics#word-count