X

Comment ajouter un compteur de caractères à la boîte de dialogue des extraits ?

Snippets by IsItWP

Vous cherchez un moyen d’ajouter un compteur de caractères à la boîte méta de l’extrait ? Bien qu’il existe probablement un plugin pour cela, nous avons créé un extrait de code rapide que vous pouvez utiliser pour ajouter un compteur de caractères à la boîte métabox de l’extrait dans WordPress.

Instructions:

Tout ce que vous avez à faire est d’ajouter ce code dans le fichier functions.php de votre thème ou dans un plugin spécifique à votre site:

function excerpt_count_js(){
      echo '<script>jQuery(document).ready(function(){
jQuery("#postexcerpt .handlediv").after("<div style="position:absolute;top:0px;right:5px;color:#666;"><small>Excerpt length: </small><input type="text" value="0" maxlength="3" size="3" id="excerpt_counter" readonly="" style="background:#fff;"> <small>character(s).</small></div>");
     jQuery("#excerpt_counter").val(jQuery("#excerpt").val().length);
     jQuery("#excerpt").keyup( function() {
     jQuery("#excerpt_counter").val(jQuery("#excerpt").val().length);
   });
});</script>';
}
add_action( 'admin_head-post.php', 'excerpt_count_js');
add_action( 'admin_head-post-new.php', 'excerpt_count_js');

Note : Si c’est la première fois que vous ajoutez des extraits de code dans WordPress, veuillez vous référer à notre guide sur comment copier/coller correctement des extraits de code dans WordPress, afin de ne pas casser accidentellement votre site.

Si vous avez aimé cet extrait de code, n’hésitez pas à consulter nos autres articles sur le site comme : 9 meilleurs plugins WordPress pour les événements et comment créer de superbes formulaires d’optin WordPress.

Commentaires   laisser une réponse

  1. Hi, Is it possible to do this for the content editor?

    1. Patricia Sarsfield septembre 24, 2020 à 11:34 am

      Try this, for the comments/replies:

      function excerpt_count_js(){
      if ( ‘post’ == get_post_type() ) {
      echo ‘jQuery(document).ready(function(){
      jQuery(“textarea#comment”).after(“Excerpt length: character(s).”);
      jQuery(“#excerpt_counter”).val(jQuery(“#comment”).val().length);
      jQuery(“#comment”).keyup( function() {
      jQuery(“#excerpt_counter”).val(jQuery(“#comment”).val().length);
      });
      });’;
      }
      return;
      }
      add_action( ‘comment_form_before’, ‘excerpt_count_js’);

  2. Customizing the WordPress Admin : WPNYC Meetup Recap : Chrisdigital's Blog : Chris Carvey : NYC novembre 8, 2014 à 7:43 pm

    […] 6. Add a character counter to excerpt metabox […]

  3. Works Great!

  4. By placing code in “if (‘page’ != get_post_type()) ” condition the pages of wordpress work perfectly. May be it could help anybody.

    function excerpt_count_js(){

    if (‘page’ != get_post_type()) {

    echo ‘jQuery(document).ready(function(){
    jQuery(“#postexcerpt .handlediv”).after(“Excerpt length: / 500character(s).”);
    jQuery(“span#excerpt_counter”).text(jQuery(“#excerpt”).val().length);
    jQuery(“#excerpt”).keyup( function() {
    if(jQuery(this).val().length > 500){
    jQuery(this).val(jQuery(this).val().substr(0, 500));
    }

    jQuery(“span#excerpt_counter”).text(jQuery(“#excerpt”).val().length);

    });
    });’;
    }
    }
    add_action( ‘admin_head-post.php’, ‘excerpt_count_js’);
    add_action( ‘admin_head-post-new.php’, ‘excerpt_count_js’);

  5. TechInsideCom juin 5, 2014 à 1:55 pm

    Thanks for this great solution. Is it posible do the same thing for title box? Thanks.

    1. You can take a look at this snippet, I made a few css changes fixed things a bit.
      http://pastebin.com/gsFF8pc7

  6. Thanks so much for this one!
    Fyi, the snippet works fine even in woocommerce product page excerpt.

  7. Heracles Papatheodorou septembre 21, 2013 à 1:25 pm

    Thank you for this one!
    Made some modifications to strip HTML and make twiter ready excerpts:


    function excerpt_count() {
    echo 'jQuery(document).ready(function($){
    $("#excerpt").after('');
    function excerpt_count() {
    var count = $("#excerpt").val();
    $("#excerpt_counter").text($(""+count+"").text().length);
    }
    excerpt_count();
    $("#excerpt").keyup( function() { excerpt_count(); }); });
    ';
    }

    add_action( 'admin_head-post.php', 'excerpt_count');
    add_action( 'admin_head-post-new.php', 'excerpt_count');

    Hopefully it proves useful to someone.

  8. Thanks for the snippet. Regarding the pages issue: the script throws a javascript error when editing a page of: “TypeError: Cannot read property ‘length’ of undefined”, on this line: jQuery(“#excerpt_counter”).val(jQuery(“#excerpt”).val().length);. As I presume on a page an excerpt is not used but the hook is still called and the script is embedded in the header, so there is nowhere called ‘#postexcerpt .handlediv’ for the query to insert after and then no length value to evaluate. But you can put an if statement round the last 3 lines of the jQuery, something like: “if (jQuery(“#excerpt_counter”).length > 0){ // last 3 lines of code here }” which may fix it.

    1. This solution solved all the js issues I was having. The screen options was annoying, but a far larger problem was image scaling returning NaN and rendered unusable. All easily solved by adding the if statement, thanks a lot!

  9. I wanted to share a screencap to clarify the issue with pages. I hope this helps. https://www.dropbox.com/s/xhkv718cjcj5ep9/excerpt-counter.jpg

    1. very strange ill look into this, sorry took so long disqus stopped emailing me new comments.

  10. I’m experiencing the same issue with AJAX not working with pages. Has anyone found a solution?

  11. Daily Tip: How to Add a Character Counter to the WordPress Excerpt Box | The WordPress Experts - WPMU.org juin 9, 2012 à 10:00 am

    […] a handy little trick that I found over at wpsnipp.com recently. This snippet lets you add a character counter to the excerpt box on your post edit […]

  12. add_action( ‘COMMENT?, ‘excerpt_count_js’);
    Can we add comments?

    1. you can assign this to any item that know the ID rather then the excerpt field.

  13. Should be a default part of WordPress. Thank you… I modified it a bit to suit my needs by replacing the Excerpt instructions with the Char Count. Who needs that silly noob stuff anyway…


    function tpl_excerpt_count(){ ?>        jQuery(document).ready(function(){        var label = 'Character Count: ';        jQuery('#postexcerpt p').html(label + jQuery('#excerpt').val().length);        jQuery('#excerpt').keyup(function(){            jQuery('#postexcerpt p').html(label + jQuery('#excerpt').val().length);        });    });   

    1. Ahhh very cool not a bad idea at all, glad that I could help out!

  14. was very helpful, really thank you.

    1. No problem enjoy the snippet.

  15. Thanks for the snippet! Works great on posts but on pages I experience the same issues as Eric and B.J. – any idea what could cause this?

    Cheers,Thomas.

    1. Hi TL just tested things out and I have no issues with wordpress 3.3 and get no errors, do you think it could be another plugin you have running ? what I would do is disable all plugins you have running see if you still have problems if not then turn each one on checking to see what plugin is the cause.

      1. Hey Kevin,

        I tried it with all plugins deactivated but no change…

        It’s not that bad because I mainly use posts not pages but still. If you find or hear something please let me know!

        Thanks 
        TL

        1. are you running on the most recent version of wordpress?

        2. yes, I tested it with 3.3 and the new 3.3.1 version…!

          (I somehow cannot reply to your post just to mine…)

  16. Is there any solution for the problem with pages? Can’t use screen options and help buttons anymore under pages.

    1. Hi Marxo, I just tested things on Firefox with wordpress 3.2.1 and no issues with the help menu or other admin menus functioning. I use jQuery(document).ready(); so as to not cause any conflicts. You could give this method a try and see if this works for you,

       http://advantcomp.com/jquery-conflicts-and-wordpress-how-to-include-your-own-jquery-scripts-the-correct-way/

      Although it could be another plugin you having running so I would temporarily disable them to test things out.

      1. Thanks for your time. )

        Tried updated code. Everything is ok if you choose Pages > Screen Options / Help. Problems start  if you choose Pages > Sample Page > Screen Options / Help.

        Fresh WordPress 3.2.1 installation
        No plugins
        Twenty Eleven theme

  17. Thx for this great function. But can you help me to add character counters to text meta boxes of this wordpress plugin (More Fields): http://wordpress.org/extend/plugins/more-fields/ ?

    1. Hi Anthony, you just need to change each instance of ‘#excerpt’ to the ID of whatever the field is you want to have the TinyMCE editor displayed. 

  18. I’ve had this snippet (great feature, BTW) on my site for a few days and just discovered it (the jQuery) was conflicting with the jQuery running on the Pages section of the admin. No menus or any AJAX’y stuff was working and it only affected just the Pages (no Posts or Custom Post Types).

    Anyone else run into that issue?

    1. Hi Eric,
      Ill take a look and see if I get the same results,

  19. Bryce Wisekal juin 17, 2011 à 2:55 am

    I’d love the see the ability to include this in the actual editor itself rather than for excerpts. I’ve been searching all day for something that counts the characters inside the editor, not excerpt. This is just brilliant though. Now to hack it apart and see if I can get it to work inside the editor instead.

    Thanks so much for this fantastic contribution!

    1. Cool glad that you like the snippet! Should be fairly easy to set things up, you can change #excerpt to #content and that will already display the count but will still display the counter within the excerpt title area. The on line 03 just change “#postexcerpt .handlediv” to target the new location you want the counter to display and you are ready to go….

      1. Bryce Wisekal juin 17, 2011 à 3:43 am

        Your my new best friend 🙂 Thanks so much! I actually already did that just having a difficult time getting it placed where I want it but I’ll figure it out 😉 Your awesome man. Thanks for this fantastic contribution! 🙂

        1. Thanks, not a problem enjoy the site and don’t forget to follow us on facebook or twitter I post daily.

      2. Bryce Wisekal juin 17, 2011 à 4:10 am

        Once more, thank you. A little editing and have it nicely placed where its needed. Thanks!

        I have followed you on both Facebook and Twitter. Look forward to reading your tweets! It’s days like this I really appreciate people who blog their discoveries. Thanks once more for sharing this snippet!

        1. Sweet, enjoy the snippets.

  20. Jani Uusitalo juin 8, 2011 à 6:34 pm

    Brilliant! Usually googling for WP stuff gets me a bunch of plugins that do what I need and then try to be a kitchen sink also, but this snipped scratched an itch with surgical precision. Thank you! Too bad there isn’t a flattr link here, this would have definitely been worth flattring.

    1. @google-de31253397522fac9cf8619290aa2a8f:disqus  glad you like the snippet! In regards to flatter I have not added one yet, but I add new snippets to wpsnipp.com everyday so I’m sure ill have it soon enough.

  21. Exactly what I was looking for. Thanks very much. If I could limit how many characters were allowed in the box (to preserve the right look for the excerpt) that would also be great. However in the meantime I have simply written next to the character counter. (DO NOT exceed 320 characters)

    1. By default the excerpt is truncated at 55 characters so it should never reach that length. However you could use this snippet and define the number of characters for the excerpt.

      http://wpsnipp.com/index.php/excerpt/custom-excerpt-length/

      Keep in mind this will not stop them from typing more text into the excerpt field.

  22. (Translated by program)
    This tip is really fantastic!, I think it may even encourage users to use this feature of the system that is always overlooked but very useful.

    1. It also helps because by default I think it is a 55 char limit for the excerpt.

  23. The excerpt metabox only appears on the new post and edit post Admin pages, so the snippet can be limited to these by using the hooks ‘admin_head-post.php’ and ‘admin_head-post-new.php’ rather than ‘admin_head’, which adds the snippet to every Admin page.

    1. Good point Andrew, it is a waste to load it on every admin page. Ill make an update to the snippet, thanks for pointing that out.

Ajouter un commentaire

Nous sommes heureux que vous ayez choisi de laisser un commentaire. N'oubliez pas que tous les commentaires sont modérés conformément à notre privacy policy, et que tous les liens sont en nofollow. N'utilisez PAS de mots-clés dans le champ du nom. Engageons une conversation personnelle et constructive.

WordPress Launch Checklist

L'ultime liste de contrôle pour le lancement de WordPress

Nous avons rassemblé tous les éléments essentiels de la liste de contrôle pour le lancement de votre prochain site Web WordPress dans un ebook pratique.
Oui, envoyez-moi le gratuit !