The excerpt is great for magazine sites where only a small bunch of words can be displayed on the home page. However, the lack of a character counting functionality for the field makes it hard to know how many you already typed in. In this tutorial we will learn how to easily add a character counter for the excerpt.
Overview
To build this, we’re going to use only a JavaScript file with some jQuery based code, and a function that we will plug into the functions.php file of our WordPress theme.
Enqueuing the JavaScript in WordPress
Enter this code into your functions.php file:
define( 'THEME_URI', get_template_directory_uri() );
add_action('admin_enqueue_scripts','ilc_admin_scripts',10,1);
function ilc_admin_scripts($page) {
$post = get_post( $_GET['post'] );
$typenow = $post->post_type;
if($typenow != 'page')
if ($page == 'post.php' || $page == 'post-new.php')
wp_enqueue_script('ilc-excerpt-counter', THEME_URI .'/ilc-excerpt-counter.js', array('jquery'));
}
The first line gets the directory of your WordPress theme and then add the scripts by hooking them into the ilc_admin_scripts function if we are writing or editing a new post.
Next, we register and enqueue our JavaScript file. Replace the path and filename with your own.
Counting the chars with jQuery
We’re going to use the after function from jQuery that will allow us to add a html form field after the excerpt textarea. This text field will be used to display the character counting:
jQuery(document).ready(function(){
jQuery("#excerpt").after("<p style="text-align:center;"><small>Excerpt length: </small><input type="text" value="0" maxlength="3" size="3" id="ilc_excerpt_counter" readonly=""> <small>character(s).</small></p>");
jQuery("#ilc_excerpt_counter").val(jQuery("#excerpt").val().length);
jQuery("#excerpt").keyup( function() {
jQuery("#ilc_excerpt_counter").val(jQuery("#excerpt").val().length);
});
});
After the text field is created, we set up its value to be the length of the excerpt textarea. This will display in the text field the number of characters of the textarea (if it’s the first time, it will be zero).
We then use the keyup event to detect a new keystroke and update the number displayed in the text field.
Conclusion
With this technique you could add character counters to pretty much any textarea in your WordPress theme. For instance, Hybrid theme is bundled with fields to enter meta description and keywords but they do not have a character counter, which is cool to have, since Google only takes the first 156 characters for snippets in search result pages.