Excerpt Length Counter in the Block Editor
Shows a live character and word count under a short preview of the excerpt in the editor sidebar, colored when it is too short or too long for search results and post cards.
Opens WPIDE on
Code
// Ideal excerpt length in characters.
$wpide_excerpt_min = 120;
$wpide_excerpt_max = 160;
add_action( 'enqueue_block_editor_assets', function () use ( $wpide_excerpt_min, $wpide_excerpt_max ) {
$screen = get_current_screen();
if ( ! $screen || 'post' !== $screen->base || ! post_type_supports( $screen->post_type, 'excerpt' ) ) {
return;
}
wp_register_script( 'wpide-excerpt-counter', false, array( 'wp-plugins', 'wp-element', 'wp-data', 'wp-editor' ), '1.0', true );
wp_enqueue_script( 'wpide-excerpt-counter' );
wp_add_inline_script( 'wpide-excerpt-counter', sprintf( 'var wpideExcerptLimits = { min: %d, max: %d };', $wpide_excerpt_min, $wpide_excerpt_max ) . <<<'JS'
( function ( wp ) {
var el = wp.element.createElement;
var Panel = ( wp.editor && wp.editor.PluginPostStatusInfo ) || ( wp.editPost && wp.editPost.PluginPostStatusInfo );
if ( ! Panel ) { return; }
function ExcerptCounter() {
var excerpt = wp.data.useSelect( function ( select ) { return select( 'core/editor' ).getEditedPostAttribute( 'excerpt' ) || ''; }, [] );
var chars = excerpt.trim().length;
var words = excerpt.trim() ? excerpt.trim().split( /\s+/ ).length : 0;
var color = ! chars ? '#757575' : ( chars < wpideExcerptLimits.min || chars > wpideExcerptLimits.max ? '#d63638' : '#00a32a' );
var hint = ! chars ? 'No excerpt yet' : ( chars < wpideExcerptLimits.min ? 'a little short' : ( chars > wpideExcerptLimits.max ? 'may be cut off' : 'good length' ) );
return el( Panel, null,
el( 'div', { style: { display: 'flex', justifyContent: 'space-between', width: '100%' } },
el( 'span', null, 'Excerpt' ),
el( 'span', { style: { color: color } }, chars + ' chars, ' + words + ' words (' + hint + ')' )
)
);
}
wp.plugins.registerPlugin( 'wpide-excerpt-counter', { render: ExcerptCounter } );
} )( window.wp );
JS
);
} );
Notes
Adjust $wpide_excerpt_min and $wpide_excerpt_max (characters) to match your theme's cards.
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.