When I’m using WordPress’ Status Post Format, I like to keep it to 140 characters, so it’s like a Tweet. But how many characters have I typed? Cos The Visual Editor only shows Word Count. So I took a look around and saw various ways of doing it, quite a few using regex to strip ‘unwanted characters’—but a space counts as a character! So I wrote my own, based loosely on what I’d been using for counting characters in the Excerpt, and from a few different plugins and bits of code. Turned out to be surprisingly easy and uncomplicated (I say that now, of course).
So, first I need a function to call a couple of files if I happen to be editing a Post or Page:
function supernaut_character_count( $charcount ) {
if ( 'post.php' == $charcount || 'post-new.php' == $charcount ) {
wp_enqueue_style( 'character-count-css', get_stylesheet_directory_uri() . '/css/char-count.css', array() );
wp_enqueue_script( 'character-count-js', get_stylesheet_directory_uri() . '/js/char-count.js', array( 'jquery' ), '20160519', true );
}
else return;
}
add_action( 'admin_enqueue_scripts', 'supernaut_character_count' );
Then I slap together some jQuery:
jQuery( document ).ready( function( $ ) {
if( $( '.post-php' ).length || $( '.post-new-php' ).length ) {
$( '#post-formats-select input' ).click( function() {
if ( $('#post-format-status').is(':checked') ) {
$( '#post-status-info tr:first-child' ).after( 'Character count:
‘ ); $( ‘#content_ifr’ ).ready( function () { setInterval( function() { var tinymcebody = $( ‘#content_ifr’ ).contents().find( ‘body’ ); $( ‘#postdivrich .character-count’ ).html( tinymcebody.text().length ); }, 500 ) }); } else { $( ‘#post-status-info tr:first-child’ ).nextAll().remove(); } }); } });
Then a miniscule bit of CSS:
.post-php #wp-character-count {
font-size: 12px;
line-height: 1;
display: block;
padding: 0 10px 4px;
}
It’s a little bodgy, and if I had more than the 45 minutes to a) work out how the Visual Editor can be fiddled with, and b) write something that worked and looked ok—the bare minimum really—I’d do it slightly nice and maybe consider for a minute throwing it into a plugin (where it officially belongs). But I won’t. It does what I want: live updating of how many characters I’ve written in the Visual Editor, and shows it in a line underneath the Word Count (also aided me in delaying writing a residency application on the day it’s due).
