MacBook avec code sur un bureau

WordPress – Compteur de caractères pour le champ caption d’une image

Pour chaque image de WordPress, nous pouvons ajouter une légende ou un titre. Il peut être utile d’y ajouter un compteur.

Compteur de caractères sous le champ caption d'une image WordPress

Pour ce faire, il faut utiliser les deux hooks admin_head-post.php ainsi que 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');