31 | Automatically Shorten the Manual Excerpt

g+

When you are building or modifying a wordpress theme, you have the choice of either using ‘the_content()’ to show the full article, or ‘the_excerpt()’ to show a shorter version.
By default, the latter limits the output to the first 55 words of the post, and automatcally strips formatting and images.
To make things more flexible, the editor also allows you to add a manual excerpt that will have preference before the automatically generated one.
There is no default limit to the length of this manual excerpt, which might break some carefully designed templates.

To apply the excerpt length limit to all excerpts, a modification of a core wordpress function ‘wp_trim_excerpt()’ would be needed.
However, changing core files is not a good idea, as the changes will be lost after each update.

Luckily, the same result can be achieved by using a fillter hook on ‘get_the_excerpt’; the code for it is added to functions.php of the theme.

(updated to utilize the filters ‘excert_length’ and ‘excerpt_more’ – aug 2010)

function wp_trim_all_excerpt($text) {
// Creates an excerpt if needed; and shortens the manual excerpt as well
global $post;
  $raw_excerpt = $text;
  if ( '' == $text ) {
    $text = get_the_content('');
    $text = strip_shortcodes( $text );
    $text = apply_filters('the_content', $text);
    $text = str_replace(']]>', ']]>', $text);
  }

$text = strip_tags($text);
$excerpt_length = apply_filters('excerpt_length', 55);
$excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
$text = wp_trim_words( $text, $excerpt_length, $excerpt_more ); //since wp3.3
/*$words = explode(' ', $text, $excerpt_length + 1);
  if (count($words)> $excerpt_length) {
    array_pop($words);
    $text = implode(' ', $words);
    $text = $text . $excerpt_more;
  } else {
    $text = implode(' ', $words);
  }
return $text;*/
return apply_filters('wp_trim_excerpt', $text, $raw_excerpt); //since wp3.3
}

remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'wp_trim_all_excerpt');

edit: expanded to take remove shortcode from the excerpt; 12/07/2010
edit: adapted to wp3.3; 16.01.2012

thanks to michael.oeser for his well written article: Wie man WordPress Textauszüge mit the_excerpt individuell anpasst. It contains even more details on how to tweak the excerpt.

This entry was posted in Tips & Tricks, WordPress and tagged , , , , , , , . Bookmark the permalink.

37 Responses to Automatically Shorten the Manual Excerpt

  1. Sherlyn comments:

    The ONE thing that they will try to push you off of is this. An-eiWhttis, of any sort, are pushing GENOCIDE in every White country and ONLY in White countries. This charge cannot be answered because it's true, it's brazen, it's out in the open.

  2. Susanne comments:

    What’ѕ up, I desire tо subscribe for this web site tօ ߋbtain moѕt reсent updates,
    tһerefore whwre cɑn i ԁߋ it ρlease assist.

    Jangan sungkan unttuk mengunjungi web Saya demi mendapatkan Fakta
    lebih lengkap mengenai cerita dewasa .
    Τhanks ya

  3. Cory comments:

    Works perfectly for what I need! thanks.

    • Rock replies:

      Lovely images. I too enjoy the stock photos and would like to use the susatinable one for a non-profit newsletter urging students to take action against climate change.

  4. Chris comments:

    I put the code at the end of my functions.php – it works for search results, but not for any archive pages – whether categories or author.

    The search.php and archive.php seem to have very similar code in them. What would be the reason for this?
    Thanks

    • alchymyth replies:

      the code will work only on ‘the_excerpt()’ – does the archive.php also use ‘the_excerpt()’ in the loop? what theme are you working with?

      • Trish replies:

        By February 14, 2008 – 10:59 pmBullet-Proof Your Bue8ssns&#i230;Personal loans can be obtained for any purpose. Whatever your need might be, lenders are there to offer you personal loans. Lenders offer personal loans for the unemployed….

  5. Howie Douglas comments:

    Thank you so much! I know this post is quite old but it’s quite surprising how hard it was to find out how to do this. I had a solution for fixing the automatic excerpt lengths but whenever my client added manual excerpts, these were never affected. Using your code with slight tweaks has helped me resolve the issue!

    Thanks a lot dude 🙂

    • Marty replies:

      An gripping treatment is couturier observe. I believe that you should correspond much on this subject, it power not be a proeoncepticn mortal but generally fill are not sufficiency to utter on specified topics. To the next. Cheers like your Feeding a Family of six on a Budget! |.

  6. chris comments:

    thanx a lot for sharing your code. that’s exactly what most of us were looking for. unfortunately i’ve got this issue than i can’t fix: using your function, in the list of results (for example) all posts i’ve inserted manual excerpt in are displayed with a double ‘read more’ link… it’s just like the function add a second ‘read more’ to the default one. where may i be wrong with it? thanx you.

    • alchymyth replies:

      possibly remove this line $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]'); to get rid of one of the ‘read more’ links ? (untested)

      • chris replies:

        I did it before, hoping it was the right solution but it was not actually: indeed the second ‘read more’ is removed from the manual excerpt text, but also the one and only ‘read more’ on posts featuring automatic excerpt. A practical solution could be adding manual excerpt to all posts – quite long – but in this case there’ll remain the issue with pages for which I have not excerpt field in the panel. Thanx.

      • chris replies:

        Finally I found the solution: the issue was caused by twenty-ten parent template. It includes function twentyten_custom_excerpt_more() which automatically add ‘read more’ tag to custom excerpt. So removing the filter in my child-template your trick works perfectly now. Thanx a lot.

      • Lavinia replies:

        Claude,A cet âge là, l’amitié était bien plus forte que l’amour…Merci pour ta visite !Dom, Non cette histoire ne me semble pas amère. Pas trop. J’ai pris beaucoup de plaisir à la revisiter. Je n’en dis pas plus, tu me diras ce que tu penses de la suite lorsque je l’aurai écrite… Ici, en tous cas, le ciel est bleu et le soleil briÃeant…Balmeylr,l§a c’est sûr !

  7. Travis comments:

    Great explanation with enough detail to easily implement. Just added to a new site running 3.3 and worked like a charm. Appreciate the post.

    • Candie replies:

      Thanks for the review! I've seen this granola all over and can&93#;t wait to try.So funny you posted this recipe today… I was literally just thinking when I woke up that I wanted rice and beans! I'd love to win some quick rice 🙂 Thanks!

  8. Jess comments:

    I think this looks like what I need, but I’m still a little stuck. I want to show a shortened (about 20 words), automatically generated excerpt on the homepage of a site, outside the loop. Could you tell me if there are any modifications I need to do this? Perhaps i’m just missing something entirely.

    I’ve managed to get the full 55 word excerpt to display using manual excerpts but that’s not really ideal.

    Hope you can help – thanks in advance!

    • alchymyth replies:

      please join the WorpPress support forum for any problems and questions.

      • Karson replies:

        HÃ¥per du hadde det fint pÃ¥ festen ;)Nydelig teppe da, hÃ¥per for all del det ikke klør for Ivars sks…ldHuyker engang jeg blogget min kjole han nevnte dette med kløinga…ha en fin fin morsdag der ute Marit!Stooor klem fra meg

  9. Damion Mishou comments:

    Hi, I like your blog Automatically Shorten the Manual Excerpt | TransformationPowerTools | for personal growth and transformation and have published it on Digg 🙂 !

    WEBMASTER!!! ENDLICH DA: Linken wie die Profis.

    cyyyaaaa!!!
    Damion Mishou

    • Latoya replies:

      Näin tiede toimii. Uusi tieto esim. geeneistä tekee Darwinin teoriasta vanasnhikaiaen.Se ei suinkaan tarkoita, että teoria olisi ollut alunperin väärä. Päinvastoin, uusi evoluutiotiede vain vahvistaa Darwinin asemaa ainutlaatuisena näkijänä.

  10. Dave Aspinall comments:

    Hey,

    Thanks for the function, works a treat! Theres a default WordPress function to check if there is an excerpt, and if not it generates one (wp_trim_excerpt). It cleans up the function quite a bit:


    function the_shortened_excerpt($length) {
    global $post;
    $text = wp_trim_excerpt($post->post_excerpt);
    $text = strip_shortcodes($text); // optional
    $text = strip_tags($text);
    $words = explode(' ', $text, $length + 1);
    if(count($words) > $length) :
    array_pop($words);
    array_push($words, ' … ');
    $text = implode(' ', $words);
    $text = apply_filters('the_excerpt', $text);
    endif;
    return $text;
    }

    • Dave Aspinall replies:

      Sorry this was for the custom short excerpt not the function above. Apologies!

    • Rosalinda replies:

      Isteni ez a leves! Többedszerre fÅ‘zöm már, de most is a fazék fölött állva kanalazok belÅ‘le, ízesítés címszó alatt, pedig ma már nem is akartam vacsorázni. Tejszín nálunk sajnos nem mehet bele, de így is szuper, sÃta-‘¼Ã¶kÅftn lettem emiatt a recept miatt, köszönet érte :))Ãœdv NürnbergbÅ‘l!

  11. Emil comments:

    Thank you very much for this post, it really helped med.

    One question though: I’m using $page->post_excerpt; to get the excerpt from my pages (I’ve a plugin which enable me to write a excerpt for my pages) but when I’m using this function, the nice function above do not apply.
    Is it possible to make the function apply to the page excerpt as well?

    • alchymyth replies:

      hi,
      i am already conversing with you in the forum;
      hope, i can answer your question there;

      alchymyth aka Michael

  12. David Alexander comments:

    If you use the two lines below you can remove the image caption also…

    $text = get_the_content(”);
    $text = preg_replace(“/\[caption[^\]]*]/”,””,$text);
    $text = preg_replace(“/\[\/caption]/”,””,$text);

  13. Chris Raymond comments:

    I tried several of the other methods I found online, none of which “kicked in”–such as:
    function custom_excerpt_length($length) {
    return 20;
    }
    add_filter(‘excerpt_length’, ‘custom_excerpt_length’, 999);

    I wish I understood why these shorter add filters did not work as they were supposed to. Using Thematic Child with WordPress 3, on a multisite. Tried the above function in my child functions.php, and it did not work. But your much lengthier function did. Why? (I am a designer not a programmer)

    • alchymyth replies:

      as you may already know, there are two kinds of excerpts
      – the handwritten excerpt (entered into the field below the post editor);
      – and the automatic exerpt.

      the ‘excerpt_length’ filter is only applied to the automatic excerpt, which is simply a truncated version of the post, which is stripped of all html tags; i.e. no images, no links, no embedded media …

      the handwritten excerpt (if shown in full) allows you to have html tags.

      if you were using handwritten excerpts, then obviously the filter does not work.

      if you are using the function of this article, then you get a consistent short excerpt (regardless if you manually type an excerpt), however always without html tags.

      • Brandy replies:

        Ady preciosa, tu entrevista te quedo de 1000, super, concreta y sustanciosa, Fel1#idades&c161;&#i61;¡¡ Y bueno que decir de la talentosisima Bety, inspiracion de muxas creo yo, con ese estilo tan romantico que le caracteriza, toda una Master en lo shabby, wow soy su Fan

    • Jacalyn replies:

      Biscuits and sweet potatoes in general are deelintfiy part of my family culinary tradition. I love biscuits, especially with cinnamon honey butter. I use a similar recipe, but I microwave my potatoes instead of roasting (it's much faster). I use the same technique for my sweet potato pie (on my blog).

  14. Jessica comments:

    Thank you so much for this piece of code! I had figured out shortening automatic excerpts, but not our manual ones (and we had quite a few — too many to edit by hand quickly). This did the trick!

    • Emma replies:

      Actually, Anna, that’s a great substitute that doesn’t have the starch-thickening problem. Amylopectin is one of the great thickeners of the cooking world, and unfortunately rice has a whole lot of it. So-called &#2ns0;gluti2ou2≵ rice actually has no “gluten” but is all amylopectin. Which is why it’s so gooey. Thanks for the comment!- Joe

  15. Cliff Aliperti comments:

    Ditto Pit above, spent 2 nights looking for this — thank you!

  16. Pit comments:

    Thank you for this post!

    I literally have been looking for this code for about 5hs.

    Keep up the great work!
    http://Pureinfotech.com

  17. Pingback: Définir une longueur d’extrait personnalisée des articles sous WordPress | WordPress Channel

    g+

    04/10/2010 | […] Cette méthode complémentaire est l’œuvre de alchymyth. […]

  18. Pingback: Tweets that mention TransformationPowerTools » Automatically Shorten the Manual Excerpt | for personal growth and transformation -- Topsy.com

    g+

    11/07/2010 | […] This post was mentioned on Twitter by Mark Sumpter. Mark Sumpter said: TransformationPowerTools » Automatically Shorten the Manual ……

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*