Custom Excerpt Function

What is a WordPress Excerpt?
A WordPress excerpt is basically a summary of a longer article, often used as a replacement on blog index and archive pages to avoid having to show the full content of each post.

Excerpts therefore allow you to slim this down by showing short summaries instead of the full text for each post.

Whether or not a theme displays excerpts is entirely up to the theme developer. However, WordPress core has a built-in functionality for handling snippets. By default, WordPress Excerpt generates an excerpt of the first 55 words of a post from the content field.

If you want to change the length of the built-in exerpt you can use this filter function. You include the function in your theme's functions.php file.

// Filter except to 20 words.
function change_excerpt_length( $limit) {
return 20;
add_filter( 'excerpt_length', 'change_excerpt_length', 999 );

How to make my own custom Excerpt function

But what if you want to...

  • show a longer or shorter excerpt and have options depending on whether it is posts, testimonials or something completely third
  • Or if you want to make use of a different meta_data from the post than get_the_content()
  • Or if you want to control your snippet on number of characters, instead of number of words

In these cases you can include this function in your theme functions.php file. This function controls the length of the number of characters and you can choose which string it will cut the text from.

function excerpt($id ,$limit)
	//$excerpt = explode(' ', $id, $limit);
    $excerpt = $id;
	if (strlen($excerpt) >= $limit) {
		$excerpt = substr($excerpt, 0, $limit).';
	} else {
		$excerpt = $excerpt;

//remove shortcodes eg
	$excerpt = preg_replace('`[[^]]*]`', '', $excerpt);

//retun data
	return $excerpt;

Then, when you want to output the function in your theme somewhere, for example when viewing a post on an archive page, do it like this 🙂

 $string = 'text text text';
$lenght = '100'; // 100 characters

//output function
echo excerpt($string, $lenght);