WordPress - Coding tutorial

How to generate multiple post excerpt lengths in WordPress

WordPress - Coding tutorialWhen you are designing or just tweaking your WordPress theme, there is a good chance that you are going to encounter a problem when you need multiple post excerpt lengths to customize your homepage or any other section of your website in a different way.

Let’s say, for example, you want to display a post excerpt of 100 characters when the homepage is showing a post with a thumbnail or image, and 250 characters for a post that don’t have a thumbnail or image, just to compensate. This article is going to help you to do just that. Keep reading to learn more.

WordPress by default has excerpt set to 55 words; to change this default behavior you could add the following code to the functions.php file in your theme directory:

function new_excerpt_length($length) {  
    return 30; // will return the 30 characters post excerpt, change this to suit your needs  
}  
add_filter('excerpt_length', 'new_excerpt_length');  

Now if you need to create multiple post excerpt lengths, you could add the following code to the functions.php file in your theme directory:

function new_excerpt($charlength) {  
   $excerpt = get_the_excerpt();  
   $charlength++;  
   if(strlen($excerpt)>$charlength) {  
       $subex = substr($excerpt,0,$charlength-5);  
       $exwords = explode(" ",$subex);  
       $excut = -(strlen($exwords[count($exwords)-1]));  
       if($excut<0) {  
            echo substr($subex,0,$excut);  
       } else {  
            echo $subex;  
       }  
       echo "[...]";  
   } else {  
       echo $excerpt;  
   }  
}  

As you can see this code does not generate a single permanent post excerpt length like the code mentioned before. What you need to do now is call the function from anywhere in your theme, for example:

  • new_excerpt (100) — This will return 100 characters post excerpt.
  • new_except (60) —¬†This will return 60 characters post excerpt.
  • and you can get the idea…

Note that you could have both functions a long the side and they will work OK.

Leave a Reply