Word Count Shortcode
Adds a [word_count] shortcode that prints how many words the current post contains, handy for long-form guides and writing portfolios.
Opens WPIDE on
Code
add_shortcode( 'word_count', function ( $atts ) {
$atts = shortcode_atts( array( 'id' => 0 ), $atts, 'word_count' );
$post_id = $atts['id'] ? absint( $atts['id'] ) : get_the_ID();
if ( ! $post_id || ( ! is_post_publicly_viewable( $post_id ) && ! current_user_can( 'read_post', $post_id ) ) ) {
return '';
}
$text = wp_strip_all_tags( strip_shortcodes( get_post_field( 'post_content', $post_id ) ) );
$count = count( preg_split( '/\s+/u', trim( $text ), -1, PREG_SPLIT_NO_EMPTY ) );
return '<span class="wpide-word-count">' . esc_html( number_format_i18n( $count ) ) . '</span>';
} );
Notes
Use [word_count id="123"] to show the count of another post.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.