Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Limit Character Count in WP Content Editor
var postTypeProject = document.getElementsByClassName('post-type-post'),
projectEditor = document.getElementById('content'),
charCount = 460;
if(postTypeProject[0] && projectEditor){
var publishBtn = document.getElementById('publish'),
theValue = projectEditor.value,
contentWrap = document.getElementById('wp-content-wrap'),
message = document.createElement('div'),
errorBox = contentWrap.getElementsByClassName('message-length'),
messageText;
function onPageLoad(){
if(theValue.length > charCount){
publishBtn.setAttribute('disabled', 'disabled');
if(errorBox[0]){
projectEditor.value = theValue.substring(0, theValue.length - 1);
} else {
messageText = document.createTextNode('Content must have less than 460 characters, currently ' + theValue.length);
message.className = 'error notice message-length';
message.appendChild(messageText);
contentWrap.appendChild(message);
}
} else if(publishBtn.getAttribute('disabled')) {
publishBtn.removeAttribute('disabled')
} else {
false;
}
}
onPageLoad();
function onChange(){
theValue = projectEditor.value;
if(theValue.length > charCount){
publishBtn.setAttribute('disabled', 'disabled');
if(errorBox[0]){
projectEditor.value = theValue.substring(0, theValue.length - 1);
} else {
messageText = document.createTextNode('Content must have less than 460 characters, currently ' + theValue.length);
message.className = 'error notice message-length';
message.appendChild(messageText);
contentWrap.appendChild(message);
}
} else if(publishBtn.getAttribute('disabled')) {
publishBtn.removeAttribute('disabled')
} else {
false;
}
}
function onInput(){
theValue = projectEditor.value;
if(theValue.length > 460){
publishBtn.setAttribute('disabled', 'disabled');
if(errorBox[0]){
projectEditor.value = theValue.substring(0, theValue.length - 1);
} else {
messageText = document.createTextNode('Content must have less than 460 characters, currently ' + theValue.length);
message.className = 'error message-length';
message.appendChild(messageText);
contentWrap.appendChild(message);
}
} else if(publishBtn.getAttribute('disabled')){
publishBtn.removeAttribute('disabled');
} else {
false;
}
}
projectEditor.addEventListener("input", onInput, false);
projectEditor.addEventListener("change", onInput, false);
}
<?php
function admin_enqueue( ) {
wp_enqueue_script( 'post_editor_limit', get_template_directory_uri() . '/assets/admin/js/app.js', false, null, true );
}
add_action('admin_enqueue_scripts', 'admin_enqueue');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment