How To Create a Variable Length Excerpt in WordPress Without a Plugin

WordPress Excerpt is a summary of your posts. In this tutorial, I will show you how to generate variable Length Excerpt that completes the sentence. Meaning that the Excerpt is not cut off mid-sentence. Also, I will show you how to preserve All, Some or None of the HTML formatting in the Excerpt, among several other features listed below.

WordPress Excerpts are generated from the post content by a WordPress filter using the function wp_trim_excerpt(). This function located in wp-includes/formatting.php of your core WordPress code.

This is my Fourth tutorial related to the WordPress Excerpt. My 3 previous tutorials are:

Manually Typed Post Excerpt

If you don´t know where and how to add a manual excerpt, read the section “How To: Manually Add a Post Excerpt” in this tutorial.

Automatically Generated Post Excerpt

In WordPress, if you do not provide a manually typed excerpt to a post, WordPress will display an automatically generated excerpt. By default, WordPress display the excerpt with the first 55 words of the post´s content, an un-linked ´[...]´ string at the end, and with all HTML tags stripped. This makes the excerpt one text paragraph without any line breaks.

CODE-Z Features

CODE-Z below has several features:

  1. No additional Plugin to your Blog. Caution about adding plugins to your theme.
  2. Option to generate a variable Length Excerpt. You have the option to complete the sentence.
  3. Option to generate a fixed Length Excerpt. You have the option to stop at exactly the defined excerpt´s word length.
  4. Option to add a ´Continue Reading´ link to the end of the Excerpt.
  5. Option to add an un-linked Ellipsis to the end of the Excerpt.
  6. Option to preserve ALL, SOME or NONE of the HTML formatting in the Excerpt.
  7. The Code counts “real words”. The code does not count the HTML tags or their content.
  8. The Advantage of step 7: No opened HTML tags in the Excerpt. No validation errors, or weird page rendering.
  9. The Code ignores Manual Excerpts and use the auto generated ones instead.
  10. The excerpt output can be uniquely styled if desired. For an example, see
    this comment
    .

Output a Variable Length Excerpt

The image below shows the result when using CODE-Z below. Notice that there are NO weird cuts in the Excerpt, the sentence is complete. Also notice that CODE-Z preserve all HTML formatting in the excerpt, and adds the ´Continue Reading´ link to the end of the Excerpt.

Excerpt sample when using CODE-Z.

To add CODE-Z: Open functions.php file located in your current theme´s folder and add (copy and paste) the following CODE-Z. Save the file and upload it to your server.

CODE-Z:
Note: To scroll within the code: You can also click on the code window and use your keyboard´s arrow keys.

<?php
/*************************************CODE-Z**********************************
*  @Author: Boutros AbiChedid 
*  @Date: May 3, 2012
*  @Websites: bacsoftwareconsulting.com/ ; blueoliveonline.com/
*  @Description: For the automatically generated Excerpt:
1. Option to generate a variable Length Excerpt.
2. Option to generate a fixed Length Excerpt. Complete the sentence in the Excerpt.
3. Option to add a 'Continue Reading' link to the text (Excerpt ending).
4. Option to add an unlinked Ellipsis to the text (Excerpt ending).
5. Option to preserve ALL, SOME, or NONE of the HTML formatting in the Excerpt.
6. The Code counts 'real words'. Does not count the HTML tags or their content.
7. Advantage of step 6: No opened HTML tags in the Excerpt. 
8. Code Ignores Manual Excerpts and use the auto-generated one instead.
*  @Tested on: WordPress version 3.3.2 
****************************************************************************/ 
	    
function bac_variable_length_excerpt($text, $length, $finish_sentence){
	 //Word length of the excerpt. This is exact or NOT depending on your '$finish_sentence' variable.
	 $length = 55; /* Change the Length of the excerpt as you wish. The Length is in words. */
	 
     //1 if you want to finish the sentence of the excerpt (No weird cuts).
	 $finish_sentence = 1; // Put 0 if you do NOT want to finish the sentence.
	  
	 $tokens = array();
	 $out = '';
	 $word = 0;
  
	//Divide the string into tokens; HTML tags, or words, followed by any whitespace.
	$regex = '/(<[^>]+>|[^<>\s]+)\s*/u';
	preg_match_all($regex, $text, $tokens);
	foreach ($tokens[0] as $t){ 
		//Parse each token
		if ($word >= $length && !$finish_sentence){ 
			//Limit reached
			break;
		}
		if ($t[0] != '<'){ 
			//Token is not a tag. 
			//Regular expression that checks for the end of the sentence: '.', '?' or '!'
			$regex1 = '/[\?\.\!]\s*$/uS';
			if ($word >= $length && $finish_sentence && preg_match($regex1, $t) == 1){ 
				//Limit reached, continue until ? . or ! occur to reach the end of the sentence.
				$out .= trim($t);
				break;
			}	
			$word++;
		}
		//Append what's left of the token.
		$out .= $t;		
	}
	//Add the excerpt ending as a link.
	$excerpt_end = ' <a href="'. get_permalink($post->ID) . '">' . ' Continue Reading &raquo;' . '</a>';
	
	//Add the excerpt ending as a non-linked ellipsis with brackets.
	//$excerpt_end = ' [&hellip;]';
	
	//Append the excerpt ending to the token. 
	$out .= $excerpt_end;
	
	return trim(force_balance_tags($out)); 
}

function bac_excerpt_filter($text){
	//Get the full content and filter it.
	$text = get_the_content('');
	$text = strip_shortcodes( $text );
	$text = apply_filters('the_content', $text);
	
	$text = str_replace(']]>', ']]&gt;', $text);
	
	/**By default the code allows all HTML tags in the excerpt**/
	//Control what HTML tags to allow: If you want to allow ALL HTML tags in the excerpt, then do NOT touch.
	
	//If you want to Allow SOME tags: THEN Uncomment the next line + Line 80.
	//$allowed_tags = '<p>,<a>,<strong>'; /* Here I am allowing p, a, strong tags. Separate tags by comma. */
	
	//If you want to Disallow ALL HTML tags: THEN Uncomment the next line + Line 80, 
	//$allowed_tags = ''; /* To disallow all HTML tags, keep it empty. The Excerpt will be unformated but newlines are preserved. */
	//$text = strip_tags($text, $allowed_tags); /* Line 80 */
	
	//Create the excerpt.
	$text = bac_variable_length_excerpt($text, $length, $finish_sentence);	
	return $text;
}
 //Hooks the 'bac_excerpt_filter' function to a specific (get_the_excerpt) filter action.
  add_filter('get_the_excerpt','bac_excerpt_filter',5);
?>

Watch out: If you are using the <!–more–> tag in your post content, make sure that it resides outside your defined excerpt length. If there is a More tag in your post, then the excerpt word count stops at either where the More tag is placed. Or depending on your parameters, it stops at your defined excerpt length, or at the end of the sentence, whichever comes first.

The sentence is considered as complete, when it ends with a dot, a Question mark, or an Exclamation mark.

CODE-Z works on WordPress 3.0 and higher. But I hope that you will always upgrade to the latest version.

To test the Regular Expression on line 30 and Line 41, you could use this Regular Expression Test Tool.

CODE-Z ignores the manually typed excerpt. The code works only for the automatically generated Excerpts. If you want to output the manually typed excerpt for your posts, then this code is not for you (or at least the code needs to be modified).

CODE-Z preserves ALL HTML formatting in the Excerpt.

Acknowledgement: Thanks to basvd, some sections of this code has been used from the Advanced Excerpt Plugin.

How To: Preserve Some HTML Formatting in CODE-Z

CODE-Z preserves ALL HTML formatting in the Excerpt. If you want to keep some defined HTML tags. For example, if you like to keep the p, a, strong tags then Comment Out lines 76 and 80 respectively of CODE-Z. Add any other tags that you want to allow separated by a comma.

How To: Remove All HTML Formatting in CODE-Z

CODE-Z preserves ALL HTML formatting in the Excerpt. If you want to disallow ALL HTML tags, then Comment Out lines 79 and 80 respectively of CODE-Z. In this case the excerpt will be displayed as unformatted text. The only exception is that new lines are preserved.

How To: Change the Excerpt Length in CODE-Z

CODE-Z is set at the Excerpt length of 55 words, plus as many more words as needed to complete the sentence. If you like to change the auto-generated Excerpt length, then find line 20 of CODE-Z and replace it with the integer that you wish. Keep the length reasonable.

How To: Replace the Excerpt More in CODE-Z

CODE-Z is set to add a ´Continue Reading´ link to the end of the Excerpt (as shown in the image above). Of course you can change the anchor to something else like ´Read More´. If you want WordPress to output an un-linked “[...]” at the end of the excerpt, then Comment line 53 and Comment Out line 56 respectively.

How To: Set the Excerpt to a Fixed length in CODE-Z

CODE-Z is set to generate a variable Length Excerpt. Meaning that the sentence will be completed, and not cut in the middle. If you want to output a fixed Length Excerpt that stops at exactly your defined word length, then replace integer 1 by 0 in Line 23.

Conclusion

In this tutorial, I showed you how to generate variable Length Excerpt that completes the sentence, with no weird-cuts. The code also counts “real words”, it does not count the HTML tags or their content with the advantage of NO opened HTML tags in the Excerpt, and no validation errors. In addition, I showed you how to preserve ALL, SOME or NONE of the HTML formatting in the Excerpt. I also revisited the excerpt_more and excerpt_length filters.

Do you have any questions? Or anything else to say? If so, please share your opinion in the comments section. Your opinion matters, unless it is a Spam.

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 Drupal & WordPress developer, Web developer, Web designer, Software Engineer and Blogger. 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 Twitter, and LinkedIn.
Visit Boutros AbiChedid Website.

29 Responses to “How To Create a Variable Length Excerpt in WordPress Without a Plugin”

  1. Denise says:

    This is very helpful – thank you! Is there any way that it could be modified to show a different excerpt length (the entire post) for just one category?

    (For instance, in most category archives I’d like an excerpt length of 200 characters – however, in just one category, I’d like to show the entire post.)

    Thanks again!
    best,
    Denise