How To Improve WordPress Excerpt Without a Plugin

In this tutorial I will show you how to enhance WordPress Excerpt by using simple functions and without the need of a plugin. WordPress Excerpt is an optional summary of your content.

The relationship between the Manual Excerpt, Automatic Excerpt, and Teaser is this: When a post has no manual excerpt and the post template uses the the_excerpt() tag, WordPress automatically generates an excerpt by selecting the first 55 words of the post followed by the unlinked ellipsis “[...]”. When the post template uses the the_content() tag, WordPress will look for the More tag and create a teaser from the content that precedes the More tag.

In WordPress, the_excerpt() template tag displays the excerpt of the current post with an un-linked ´[...]´ at the end. If you do not provide a manually written excerpt to a post, it will display an automatic excerpt which by default refers to the first 55 words of the post´s content. Also in the latter case, HTML tags and graphics are stripped from the excerpt´s content.

What about a Plugin? Yes, there are plugins that customize WordPress auto-generated excerpt. But haven´t you read my previous post about the disadvantages of going crazy adding plugins to your theme? In addition, aren´t you eager to learn and do things yourself?

How To: Change the Excerpt Length

From WordPress Version 2.8.0 and above you can change the excerpt length from the default 55 words. Open the functions.php file located in your current theme´s folder and add (copy and paste) the following code.

Code1 (Valid for WordPress Version >= 2.8.0)

<?php 
function custom_excerpt_length( $length ) {     
	return 35; //Change this number to any integer you like.
}
add_filter( 'excerpt_length', 'custom_excerpt_length' );
?>

References:

How To: Change the Excerpt More String

By default, the excerpt more string at the end is set to ´[...]´. To change the default excerpt more string, add the following code to your theme´s functions.php file:

Code2 (Valid for WordPress Version >= 2.9.0)

<?php 
function custom_excerpt_more( $more ) {     
return ' ...'; // nicer without the brackets, but not very useful. 
}
add_filter( 'excerpt_more', 'custom_excerpt_more' );
?> 

Code2a (Valid for WordPress Version <= 2.8.x)

<?php 
function custom_excerpt_more( $excerpt ) {
	return str_replace( '[...]', '...', $excerpt );
}
add_filter( 'wp_trim_excerpt', 'custom_excerpt_more' );
?>

References:

How To: Replace the Excerpt More String with a Link

By default WordPress outputs an un-linked “[...]” at the end of each excerpt, which is not useful for Accessibility and SEO purposes. Open your theme´s functions.php file, and add the following code.

Code3a (Valid for WordPress Version >= 0.7.1)

<?php 
function custom_excerpt($text)   
{   
	return str_replace('[...]', '<a href="'. get_permalink($post->ID) . '">' . '&raquo; Continue Reading.' . '</a>', $text); 
}   
add_filter('the_excerpt', 'custom_excerpt');  
?>

If you want to add the post title to your link in the excerpt, then add the following code to your theme´s functions.php file.

Code3b (Valid for WordPress Version >= 0.7.1)

<?php 
function custom_excerpt($text)   
{   
  return str_replace('[...]', ' &#8230;<br /><a href="'. get_permalink($post->ID) . '">' . 'Continue Reading: '. get_the_title() . '</a>', $text);  
}   
add_filter('the_excerpt', 'custom_excerpt');  
?>

If you are using WordPress Version 2.9 and above you can use the following code.

Code3c (Valid for WordPress Version >= 2.9)

<?php
function custom_excerpt_more($more)   
{  
   return ' <a href="'. get_permalink($post->ID) . '">' . '&raquo; Continue Reading.' . '</a>';
}   
add_filter('excerpt_more', 'custom_excerpt_more');  
?>

If you want to add the post title to your link in the excerpt, add the following code to your theme´s functions.php file.

Code3d (Valid for WordPress Version >= 2.9)

<?php
function custom_excerpt_more($more)   
{  
  return  ' &hellip;<br />' . '<a href="'. get_permalink($post->ID) . '">' . 'Continue Reading: '. get_the_title() . '</a>'; 
}   
add_filter('excerpt_more', 'custom_excerpt_more');  
?>

WARNING: You can ONLY add to your theme´s functions.php, Code3a, or Code3b, or Code3c, or Code3d, but not all or any combination.

References:

How To: Change Excerpt Length Depending on the Category

If you want to modify the excerpt length based on the category, then add the following code to your theme´s functions.php file. Don´t forget to change the category ID to yours.

Code4a (Valid for WordPress Version >= 2.8.0)

<?php
function custom_excerpt_length($length) {
    if (in_category(4)) {  //For posts belonging to category ID 4
        return 65;
    } else {
        return 40; //for all others, return 40 words.
    }
}
add_filter('excerpt_length', 'custom_excerpt_length');
?>

If you want to modify the excerpt length based on multiple categories, then add the following code to your theme´s functions.php file instead. Don´t forget to change the category IDs to yours.

Code4b (Valid for WordPress Version >= 2.8.0)

<?php
function custom_excerpt_length($length) {
    if(in_category(array(4,40))) {  //For posts belonging to category IDs 4 and 40
        return 65; //return 65 words for the excerpt
    } else {
        return 40; //for all others, return 40 words.
    }
}
add_filter('excerpt_length', 'custom_excerpt_length');
?>

WARNING: You can ONLY add to your theme´s functions.php, Code1, or Code4a, or Code4b, but not all or any combination.

If there is a More tag in your post, then the excerpt word count stops at either where the More tag is placed, without the excerpt trailing characters, or your defined excerpt length, whichever comes first. Therefore make sure that you place the More tag outside your specified excerpt word count.

If you don´t know how to find the Category ID, then read my previous tutorial.

Troubleshooting

If you are having problems with any of the code blocks above, please note the following:

  1. The filters only work on excerpts that are automatically generated by WordPress. The filters do not affect the manually typed excerpts.
  2. The filters only work on excerpts that use the_excerpt() template tag.
  3. Check your plugins. Some plugins contain code that overrides the excerpt.

References:

How To: Replace the_content() With the_excerpt

Never show full posts in the main page. In your theme, If you have the_content() template tag, make sure to use the More tag in your post. They work together, otherwise your posts will be shown in full in the main page which can dramatically slow page loading speed. For example let´s say you display 8 posts in your main page, and by showing every post in full, then it will take long time for the page to load and for the user to scroll. One way to reduce page load time, is to replace the_content() template tag with the_excerpt() template tag.

To do that, open the index.php file located in your theme´s folder and replace the the_content() with the_excerpt(). Also you could do the same for archive.php and search.php files. (DO NOT TOUCH page.php or single.php files.)

Code5

//The '...' can be anything inside. 
//Search and Replace the_content() template tag
<?php the_content('...'); ?>

//With the_excerpt() template tag
<?php the_excerpt('...'); ?>

NOTE: the_excerpt() template tag has no parameters. However, there is no harm from keeping them in case you wanted to revert back and use the_content() again. If you get any errors, then replace the_content(‘…’); with the_excerpt();.

To EMPHASIZE: the_content() template tag is used in conjunction with the More tag. Make sure to place the More tag somewhere at the beginning of the post. Otherwise, the whole content of the post will be displayed.

Reference:

How To: Manually Add a Post Excerpt

To manually add an excerpt to a post, you need to login to your WordPress dashboard, find your post, and add the excerpt as shown in the picture below:

Manually adding an excerpt in WordPress dashboard.

The Advantage of a Manual excerpt is that they are often used by search engines to describe search results. In this CASE, good excerpts increase and improve Website traffic. Also, WordPress preserves HTML formatting in manual excerpts which is not the case for the automatically generated excerpt. Another major drawback of the automatic excerpt is that the beginning of a post is usually an introduction and not a summary.

When using the manually typed excerpt feature, the ´[...]´ is not automatically added nor a link to a page containing the full post. However, to bypass this shortcoming you need to replace the_excerpt(); in your theme´s index.php (and also in your theme´s archive.php and search.php files) with the following code below. The beauty about this code is that it takes care of both scenarios: the manually added and the automatically generated excerpts; which means that you can have both manual excerpts and auto-generated excerpts for your posts with no issues.

Code6

//In your theme files: Search and Replace the_excerpt() template tag
<?php the_excerpt(); ?>

//With the following code:
<?php 
//Add Links to Manual and Automatic excerpts
if ( $post->post_excerpt ){ //If manual excerpt is added
    //Add a link at the end of the manual excerpt 
    the_excerpt();?>
    <p><a href="<?php the_permalink(); ?> "> &raquo; Continue Reading: <?php the_title() ?></a></p>
<?php }
else {//else, it is an automatic excerpt, then let the filter handle it.
     the_excerpt();
     }
?>		

How To: Only Display a Post´s Excerpt if it Exists

If you only want WordPress to display a manually added excerpt and you don´t want WordPress to automatically generate any excerpts for you, then in your theme files (index.php, archive.php and search.php), then follow the instructions in the code below:

Code7

//Replace the_excerpt() template tag 
<?php the_excerpt(); ?> 

//With this:
<?php if ( $post->post_excerpt ) the_excerpt(); ?>

General Warning

When you add several PHP code blocks in your theme´s funtions.php file, make sure that you don´t leave any whitespace (spaces, newline) before the opening PHP tag or after the closing PHP tag. Like so (the correct way):

<?php 
//Some Code here beetween the opening PHP tag (above) 
//and the closing PHP tag (below)...
?>
<?php 
//Some other Code here ...
?>

In the above code, if you leave any whitespace or a newline between lines 4 and 5, you will get the following error: Warning: Cannot modify header information – headers already sent by (… , in your login screen and after you login to your WordPress dashboard.

General Advice

Keep WordPress Up to Date. If you can, you should always have the latest version of WordPress. Upgrading to the latest version is necessary because upgrades usually include performance and security enhancements and also new features. Go and download the latest version.

Excerpt Definition Revisited

The manually typed excerpt is a short description of your post typed in the Excerpt field in your Administration Panels. The excerpt is used to describe your post in RSS feeds and is typically used in displaying posts summary in the main page, in search results, in archives, and category views. You must use the the_excerpt() template tag to display the contents of this field. If you do not type any information in the post´s Excerpt field, and you use the_excerpt() in your theme files, then WordPress will automatically generate the Excerpt of your post.

The excerpt should not be confused with the teaser. When typing a long post you can insert the <!--more--> Quicktag after a few sentences to act as a cut-off point. When the post is displayed, the teaser, followed by a hyperlink (such as Read the rest of this entry…), is displayed. Your visitor can then click on that link to see the full content of your post. the_content() template tag should be used to display the teaser.

Conclusion

These simple functions, help you enhance the default WordPress excerpt without the need of a plugin. Do you have any other suggestions? or anything else to say? If so, please share your opinion in the comments section. Your opinion matters, unless it is a Spam.

As you already know by now, the automatically generated excerpt is stripped from all graphics and HTML tags. In my next tutorial, I will discuss how to keep HTML formatting in the excerpt (and you get to choose which tags to include), so go ahead and read it!

General Reference

If you found this post useful, please consider: linking back to it, subscribing by email to future posts, or subscribing to the RSS feed to have new articles delivered to your feed reader, or feel free to donate. Thanks!

About the Author |
Boutros is a professional freelance Web designer, Web developer, Software Engineer, and Blogger. He is the Chief developer at Blue Olive Online. He strives for pixel perfect design, clean robust code, and user-friendly interface. If you have a project in mind and like his work, feel free to contact him. Connect with Boutros on StumbleUpon, Twitter, and LinkedIn.
Visit Boutros AbiChedid Website.

42 Responses to “How To Improve WordPress Excerpt Without a Plugin”

  1. Matt N says:

    This is a great post! Thanks so much! I just have one question… Does anyone know the code I can use to make the excerpt only stop after complete sentences, so that it doesn’t cut off mid-sentence?

    I know there is a plugin that does this, but I tried it, and it caused issues with my theme.

    Thanks!

  2. [...] This tutorial is a continuation of my two previous tutorials: How To preserve HTML Tags in WordPress Excerpt and How To Improve WordPress Excerpt. [...]

  3. Hi Boutros AbiChedid,

    I want the automatic excerpt excludes particular part of the post.

    Here is the situation: Single.php in theme I used automatically generate ‘table of content’ of the post before callting the_content(). Because of that the table of content is included into the post excerpt. I want to exclude it. Do you have any suggestion how to do that?

    Thank you.

  4. I was looking for a way to add a more tag after manual excerpt (and of course I wanted the possibility to use auto-generated excerpt with more tag as well – for when I don’t feel like typing the excerpt.

    Anyway, your code 6 does the trick!

    I put it in the blog-category template, replaced

    with lines 5-15 in code 6, but I got an error warning in Dreamweaver (yes I know, but I’m a designer not computer wander child) and when I tested it in Firefox there was a php error due to wrongly placed } …!

    So what worked for me? There is a missing space in the line 11 of code 6, I think.
    <?php}
    should be
    <?php }

    The Dreamweaver AND Firefox stoped complaining and everything works as it should! Sooo yes! Code 6 works! Thank you thank you thank you!

    • Still didn’t managed to post all the code in the code tags above, but I’m improving :)

      Now, there is another question – it’s not really important one, but… So now
      the auto-generated excerpt more tag works
      and
      manual excerpt more tag works

      but if, for example, my client messes up and uses WP built-in tag… then there is no read more link after it! :P

      As I said, nothing too serious, but maybe something to think about. :)

      • Oh, I’ve just read that the WP built-in tag uses the_content not the excerpt, so forget my previous rambling…
        Is there any chance your code 6 can be used in functions.php file?

        • Yes, it can be added to the functions.php file. But I don’t see the benefit, since you still have to modify the relevant theme files with the new template tag.
          The code is too small to start with. So it doesn’t make any difference.
          I am happy where it’s put outside the functions.php file.
          Boutros.

    • Thanks Neja, you are right there was a missing space in line 11 (I corrected it). Interesting, when I tested the code it did not cause an error for me.
      Boutros.

  5. Hello!
    I’m also trying to use code 6 and have the same problems as mentione above. I took the whole line:

    and replaced it with:

    post_excerpt ){ //If manual excerpt is added
    //Add a link at the end of the manual excerpt
    the_excerpt();?>
    <a href=" “> » Continue Reading:

    Please help, I was searching for sooo looong for something like this!

  6. yuri says:

    thanks, your code is much better than plugins like auto exceprt or auto excerpt everywhere.
    They are pretty hard to implement due I’m using framework.
    great post.

  7. pribadi says:

    Hi,
    Thank you for your comprehensive tips.
    I am using twenty eleven, and trying to figure out how to show the first image “and” the first paragraph of each post, on the home page. If no image present at the beginning of the artcle, it will only show the first paragraph and the “read more” link after that.

    Actually, I got the idea from here http://wordpress.org/support/topic/plugin-auto-read-more-generator-mod-for-video

    I don’t have enough knowledge to insert this in twenty eleven theme. Hope you don’t mind helping me here.

    Regards,
    pribadi

    • Hi pribadi,

      I wrote a post on how to do exactly that. Why don’t you carefully read the article: How To preserve HTML Tags in WordPress Excerpt Without a Plugin.
      Let me know if you still have trouble. Then I will install the twenty eleven theme and test … and I will show you how it is done.

      Boutros.

      • pribadi says:

        Hi,
        Thank you for your quick reply. I already skim your article. I need to emphasize that I am totally newbie in this matter. So, certainly I will reread it again soon. But my newbie question is, since the post in twenty eleven is controlled by functions.php “and” content.php, where should I put your functions? Some people even suggest I should use child theme instead?
        So far I only manage to use automatic excerpt in my twenty eleven blog by inserting this
        in content.php ( I got it from WP forums). But I failed to insert the first image on the excerpt.

        Thanks again for your help.

        Pribadi

        • pribadi says:

          Hi,
          Sorry, the functions didn’t show up in my previous comment.

          So far I only manage to use automatic excerpt in my twenty eleven blog by inserting this () in content.php.
          But I failed to insert the first image on the excerpt.

          Thanks again for your help.

          Pribadi

        • Hi pribadi,
          I installed the twenty eleven theme. You are frankly all set with what you want to do. The theme is coded in a way to preserve ‘HTML formatting’ in the excerpt, i.e it keeps your images and links and others.
          If you want to just show the first paragraph in your posts, all what you have to do is add the more link (<!–more–>) at the end of the first paragraph of each post. Add the more tag immediately after the closing of the p tag (after </p>).
          If you just want to keep only the image as part of your first paragraph and not other tags (like hyperlinks, bolded font) then you need to add extra functions.

          You can check how my blog behaves with the twenty eleven (temporary) link in the ‘CHANGE THEME’ widget at the right sidebar:
          Notice that the posts in the main page show more than one paragraph because it all depends where you add the more link (<!–more–>)

          Let me know if this helps (or not).

        • pribadi says:

          Hi Boutros,

          I really appreciate your tutoring. Your temporary example is good, except it seems you have to do it manually ? (for placing the “more link”)

          So far, I am able show “automatic excerpt” on the homepage (without any image) by changing
          “” into
          “” in content.php.

          But, what I really want is actually to show “automatically” the first paragraph and the image (if available, but not the thumbnail) of every posts, on the homepage .

          I got some codes from a forum that “might” work :
          http://wordpress.org/support/topic/plugin-auto-read-more-generator-mod-for-video

          But my problem, as a newbie, I really don’t know where exactly to insert them :-(
          So, your step by step guidance is highly needed.

          regards,
          pribadi

        • Hi Pribadi,

          If it is up to me, the simplest way is to do it manually as I described earlier. If you are writing posts manaullay (and not harvesting them) then you have to add the more link anyway.
          There is a plugin to do what you want called: Auto Read More Generator (http://wordpress.org/extend/plugins/auto-read-more-generator/).
          I don’t favor the use of plugins unless it is absolutely necessary. Read my previous post about: Caution! Adding Plugins to Your WordPress Theme.
          If you decide to use the above plugin, make sure to follow the Installation instructions. Basically from the dashboard find the ‘Auto Read More Generator’ and then install and activate it. Then replace the ‘the_content’ with ‘the_content_with_readmore_link’ in the following 2 files: content.php on line 41 and content-intro.php on line 17. These 2 files are located in the ‘twentyeleven’ theme folder.
          I tested the plugin with partial success. It seems that sometimes it adds the read more link after 2 paragraphs and not just one p especially when there is an image present. That’s why I prefer my manual method, it is more consistent.
          In any case, try it and see if it fits you.
          Good Luck.

          References (in case you don’t know):
          1. Managing Plugins: http://codex.wordpress.org/Managing_Plugins
          2. Editing files: http://codex.wordpress.org/Editing_Files
          3. FTP Clients: http://codex.wordpress.org/FTP_Clients

        • pribadi says:

          Hi Boutros,

          You are a magnificent tutor! I am sure you could expand successfully your business in online tutoring (maybe like this www . ericstips . com) for people around the globe.

          Not only you reply to my questions very quickly, but also give direct solution…..and more!

          I am from Jakarta (Indonesia), and if there is anything I could do for you, just email me and mention this thread. I do hope I can return you the favor.

          The reason I need the “automatic read more” coz i’m am trying to set up an auto amazon store, using autoblog plugin. It seems the link that I mentioned is for the revision of the “auto read more generator”. I tried to insert the complete revision codes directly to content.php (not using the plugin), but with no success. I am sure your guidance will do the magic.

          I highly appreciate your tips and guidance. Look forward to asking you different questions :-))

          Best of Luck to you forever,
          pribadi

        • Thank you pribadi. I very much appreciate your comment.
          PS. I wish I knew what you were doing to start with for the need of an auto read more.
          To replace the plugin, the code should have been added to the ‘functions.php’ file and then the tag (whatever function name you used) will be added to other
          files (it could be content.php or others) depending on the theme.
          To get an idea on how to do custom coding without the use of plugins for your theme, check out my other posts at: (http://bacsoftwareconsulting.com/blog/index.php/tag/wordpress-plugins/)
          But for now, since you are still at the learning stage (and we all are, learning is a never ending story), I think the best approach for you is to stick with a plugin.

          PS. Feel free to subscribe to my RSS feed or subscribe by Email (or donate if you like :))
          Good Luck.
          Boutros.

  8. ysidnem says:

    Hi when I use code 6 I get an error message saying there is an unexpected }. I am really wanting to limit the words in manual excerpts. Thanks

    • Hi ysidnem,

      Code6 is fine, I am using it for this blog. Make sure you are copying/replacing the whole block of code between the opening/closing php tag (<?php … ?>).
      Also you need to replace line2 of code6 when searching in your files (index.php etc.) with lines 5 through 15.

  9. Andrew says:

    Hi, Please can you tell me if there is a way to change the length of the excerpt according to the custom post type. So if I have a custom post type called “books” how I can then control the length of excerpts from it?

    Thank you so much for your post.

  10. Hi there,

    I really appreciated your post, it’s very simple and yet effective. I have a problem concerning wordpress auto-excerpt feature: everytime I share a post on fb the excerpt shows the shortcode of the plugin I use for Google Adsense, as you can see trying to share this: http://nicolozarotti.com/hotspot-wifi-di-vodafone-per-liphone-4-follia-pura/

    So I was wondering if there is any way to exclude it from the excerpt. I have already tried these codes in the function.php:

    add_filter( ‘the_excerpt’, ‘shortcode_unautop’);
    add_filter( ‘the_excerpt’, ‘do_shortcode’);

    but it didn’t work and I don’t really know what to do to prevent WP from having this annoying behaviour.

    Thank you very much,

    Nicolò

    • Hi Nicolo,

      ” fb the excerpt shows the shortcode of the plugin I use for Google Adsense”

      I don’t think I was able to understand your point. I don’t use Google addSense. Addsense is showing in your post, I don’t think that you can do anything about it. Probably there are some settings in addsense to prevent it from showing up in the excerpt.
      From the link you gave, It seems that your post shows in its entirety and not an excerpt.
      In any case, feel free to elaborate and comment again….

      Boutros.

  11. Curtis F says:

    Thanks for the great tips! I have one question on something I may not even be going about it the right way but…

    I thought of displaying the excerpt on my single post page formatted as an intro. When I use `post_excerpt ) the_excerpt(); ?>` the excerpt won’t show and when I just use `the_excerpt();` it works but displays the automatic excerpt but I only want it to show the manual excerpt.

    There must be something I don’t understand about the conditional statement.

    Any help would be greatly appreciated.

    • Hi Curtis,

      I am not sure I really followed what you are saying, but let me clarify few things:

      1. If your post displays the automatically generated excerpt but not the manual one, the first thing that come to my mind is: did you manually type an excerpt to your post? You do that in your dashboard
      (See section: How To: Manually Add a Post Excerpt refer to code6). I see that the automatically generated excerpt works fine from looking at your Website.

      2. If you already manually typed the excerpt to the post and it does not show, then I never had this problem before. WordPress core code handles that, if a manual excerpt exists then it will be displayed otherwise an automatic excerpt is generated.
      It could be that a plugin is interfering and preventing the manual excerpt to be displayed??? Try disable one plugin at a time and see if it works for you.

      3. In your comment you said: “When I use `post_excerpt ) the_excerpt(); ?>` the excerpt won’t show …”
      Are you referring to code7 in the section How To: Only Display a Post´s Excerpt if it Exists?
      The manual excerpt will not show if you did not type an excerpt for your post in your dashboard.

      Let me know if this help (or not), and feel free to comment and elaborate more.

      PS. I have a related tutorial that might be an interest to you: How To preserve HTML Tags in WordPress Excerpt Without a Plugin.

      Boutros.

  12. geraldine says:

    Hi,

    Thanks for this tutorial. it’s helpful. i have one question though, this tip works: How To: Replace the_content() With the_excerpt but there is no title. I tried changing the functions.php using the above mentioned codes but i got error.

    regards,

    geraldine

    • Hi geraldine;

      I am not sure what errors you are getting. Can you be more specific. Also it would help me if you tell me what theme you are using – the URL (I am assuming it is a free WordPress theme).
      For the Section: How To: Replace the_content() With the_excerpt

      You basically, in your theme’s folder, open the files: index.php, archive.php and search.php. Replace the the_content('...'); with the_excerpt();.
      (DO NOT MODIFY ‘page.php’ or ‘single.php’ files.)
      Let me know if this helps or not.
      Boutros.

      • geraldine says:

        hi boutros,

        thanks so much for replying. i’m using the default twenty eleven on my blog: http://archivistblog.info/ prior to last night (i spent the whole night customizing last night it was fun and frustrating at the same time), i was using a plugin to display excerpt with thumbnail. then, i found your blog which is very helpful. the ‘How To: Replace the_content() With the_excerpt’ tip works but i can’t get the title. so i ended up using the article summary instead (when you click the ‘more’ thing in the compose box). this will display the summary with picture on the homepage.

        regards,

        geraldine