Add Total Word Count to the Publish Box
Displays the post's word count inside the Classic Editor's Publish meta box and keeps it updated live in the Block Editor.
PHPby SnipCraft
php
<?php
// Classic Editor: show word count in the Publish meta box.
add_action( 'post_submitbox_misc_actions', 'scseed_publish_box_word_count' );
if ( ! function_exists( 'scseed_publish_box_word_count' ) ) {
function scseed_publish_box_word_count() {
global $post;
if ( ! $post ) {
return;
}
$count = str_word_count( wp_strip_all_tags( $post->post_content ) );
printf(
'<div class="misc-pub-section" style="border-top:1px solid #ddd;padding-top:8px;">%s <strong id="scseed-wc">%s</strong></div>',
esc_html__( 'Word count:', 'scseed' ),
number_format_i18n( $count )
);
}
}
// Block Editor: subscribe to the data store and refresh the counter live.
add_action( 'enqueue_block_editor_assets', 'scseed_block_editor_word_count' );
if ( ! function_exists( 'scseed_block_editor_word_count' ) ) {
function scseed_block_editor_word_count() {
$script = 'wp.data.subscribe( function() {
var editor = wp.data.select( "core/editor" );
if ( ! editor ) { return; }
var content = editor.getEditedPostContent() || "";
var plain = content.replace( /<[^>]+>/g, " " ).replace( /[ \t\n\r]+/g, " " ).trim();
var words = plain ? plain.split( " " ).filter( Boolean ).length : 0;
var el = document.getElementById( "scseed-wc" );
if ( el ) { el.textContent = words.toLocaleString(); }
} );';
wp_add_inline_script( 'wp-edit-post', $script );
}
}#admin#content#editor#publishing#word-count