MacBook avec code sur un bureau

WordPress – Character counter for the caption field of an image

For every WordPress image, we can add a caption or a title. It may be useful to add a counter.

Character counter under the caption field of a WordPress image

To do this, you must use both hooks admin_head-post.php and admin_head-post-new.php

function cf_caption_count_js() {
    echo '<script type="text/javascript">
jQuery(document).ready(function() {
    jQuery("#attachment_caption").wrap("<div></div>");
    jQuery("#attachment_caption").parent().css("display", "table");
    jQuery("#attachment_caption").parent().css("width", "100%");
    jQuery("#attachment_caption").after("<span id=\'cf_caption_count\' style=\'display:table-cell; width: 30px; margin-left: 5px; text-align: right;\'></span>");
    jQuery("#cf_caption_count").html(jQuery("#attachment_caption").val().length);
    jQuery("#attachment_caption").keyup(function() {
        jQuery("#cf_caption_count").html(jQuery("#attachment_caption").val().length);
    });
});
</script>';
}
add_action('admin_head-post.php', 'cf_caption_count_js');
add_action('admin_head-post-new.php', 'cf_caption_count_js');