Gearside Design

A Smarter Wordpress Excerpt Function

The excerpt function in Wordpress is great when you only want to show a preview of the post and allow users to “Continue Reading” by clicking the link. I’ve found that it can be limiting when you want to customize the excerpt on an individual basis and not globally. In order to change the “Read More” link, the ellipses, or the word limiter, you would have to make additional functions and/or globally alter the main excerpt function.

Wordpress the_excerpt(); Defaults

The default values of the core Wordpress the_excerpt(); function are as follows:
Word limit: 55
Ellipses: True

A Smarter Wordpress Excerpt Function

Here is a function that allows the developer to call a single function throughout the site while still maintaining the ability to customize each instance of the excerpt. Additionally, if the associated post does not have an excerpt, instead of returning an empty string, this excerpt function will try the content of the post instead. Place this snippet into your functions.php file.

PHP

The way to call this custom excerpt is with the following (and it is noted in the comment above the main function), and it still must be placed within the loop.

PHP

echo nebula_the_excerpt(‘Read more »’, 75, 1);

Parameters

There are three optional parameters that are passed to this function: $more, $length, and $hellip.

The first parameter is the “Read More” string. This can now be anything. It will automatically be linked with the post’s permalink. If not included, no link text will appear.

The second parameter is the integer length of the excerpt. The default value is 55 (which can be changed in opening declaration of the function itself (in the functions.php snippet where “$length=55”).

The third parameter is a boolean for an ellipses. By default, it is set to 1 (true). To turn it off, simply set it to 0.

If you are satisfied with the default values for most of the calls, you could call this excerpt using:

PHP

echo nebula_the_excerpt(‘Read more »’);