Skip to content

Instantly share code, notes, and snippets.

@lukasbesch
Last active January 27, 2022 20:58
Show Gist options
  • Save lukasbesch/5266e24b983ce05d3276 to your computer and use it in GitHub Desktop.
Save lukasbesch/5266e24b983ce05d3276 to your computer and use it in GitHub Desktop.
Character counter for ACF WYSIWYG Field
/* For usage with acf_form() */
function my_acf_wysiwyg_character_counter() {
?>
<script type="text/javascript">
acf.add_filter('wysiwyg_tinymce_settings', function(mceInit) {
mceInit.elementpath = false;
mceInit.setup = function(ed) {
var characterLimit = 800,
edContainer,
countChar,
colorOriginal;
ed.on('init', function(e) {
edContainer = $(ed.iframeElement).closest('.acf-input');
countChar = edContainer.find('.mce-statusbar .mce-flow-layout')
.prepend('<div class="mce-path mce-flow-layout-item mce-first count-char"><span class="count-char-current">0</span><span>/' + characterLimit + '</span></div>')
.find('.count-char-current');
colorOriginal = countChar.css('color');
});
var limit = function(e) {
var node = ed.getBody(),
text = (node.innerText || node.textContent),
textTrim = text.trim(),
length = (textTrim.length === 0) ? 0 : text.length;
if (length > characterLimit) {
countChar.css('color', 'red');
} else {
countChar.css('color', colorOriginal);
}
countChar.text(length);
};
ed.on('change', limit);
ed.on('keyup', limit);
};
return mceInit;
});
</script>
<?php
}
add_action('acf/input/admin_footer', 'my_acf_wysiwyg_character_counter');
@raajtram
Copy link

I'd rename this to "Character Counter". Works well then :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment