Skip to content

Instantly share code, notes, and snippets.

@phillip-boombox
Last active December 13, 2017 18:52
Show Gist options
  • Save phillip-boombox/4d4576d2775f2160036934f1308019c4 to your computer and use it in GitHub Desktop.
Save phillip-boombox/4d4576d2775f2160036934f1308019c4 to your computer and use it in GitHub Desktop.
WordPress: Add a character counter to post excerpts in admin.
<?php
/**
* Add a character counter to post excerpts in WordPress admin.
* Action: admin_head-post.php, admin_head-post-new.php
* Inspired by @link: https://premium.wpmudev.org/blog/character-counter-excerpt-box/
*/
function cmfy_excerpt_character_counter() {
// If post type does not support excerpt, do nothing
if ( ! post_type_supports( get_post_type(), 'excerpt' ) ) {
return;
}
// Character limit
$limit = 50;
// If set to true, the textarea will prevent input beyond limit, else it'll give a notice if limit is exceeded
$hard_limit = true;
// Excerpt box character count markup
$markup = sprintf(
'<div class="hide-if-no-js" style="border: 1px solid #e5e5e5; border-top: none; background-color: #f7f7f7; padding: 2px 10px;">%s <span id="postexcerpt_char_count"></span> / %d</div>',
_x( 'Character count', 'excerpt characters', 'cmfy' ),
$limit
);
?>
<script>
( function( $ ) {
$( document ).ready( function() {
var limit = <?php echo $limit; ?>,
hard_limit = <?php echo $hard_limit ? 'true' : 'false'; ?>,
markup = '<?php echo $markup; ?>',
// Reference to the excerpt textarea
$excerpt = $( '#excerpt' ),
// Reference to the character count element after adding it to the DOM
$excerpt_char_count = $( '#excerpt' ).after( markup ).next().find( '#postexcerpt_char_count' );
// If using a hard limit, set the maxlength attribute on the excerpt textarea
if ( hard_limit ) {
$excerpt.attr( 'maxlength', limit );
}
function update_count() {
// Current count of excerpt
var count = $excerpt.val().length;
// Update DOM to reflect count
$excerpt_char_count.text( count );
// If not using a hard limit and count goes over limit, apply error-message class
if ( ! hard_limit && count > limit && ! $excerpt_char_count.hasClass( 'error-message' ) ) {
$excerpt_char_count.addClass( 'error-message' );
} else if ( ! hard_limit && count <= limit && $excerpt_char_count.hasClass( 'error-message' ) ) {
$excerpt_char_count.removeClass( 'error-message' );
}
}
// Update count on keyup which should catch most methods in which data is entered
$excerpt.on( 'keyup', update_count );
// If pasting not using a keyboard, do it this way
$excerpt.on( 'paste', function() {
setTimeout( update_count, 0 );
} );
// Go!
update_count();
} );
} )( jQuery );
</script>
<?php }
add_action( 'admin_head-post.php', 'cmfy_excerpt_character_counter' );
add_action( 'admin_head-post-new.php', 'cmfy_excerpt_character_counter' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment