The WordPress Excerpt functionality has been part of the WordPress core for a long time and is used widely in blog themes. Although its behaviour is customisable through the use of filters, I have adopted a different approach over recent years to provide ease of use and flexibility to administrators, whilst keeping implementation consistent throughout bespoke theme templates and partials. You may also want to truncate content from a custom field, in which case using the default excerpt functionality wouldn’t work.

The idea is that the administrator can choose whether or not they want to add a bespoke snippet to their post or custom post type, if they do then they use the excerpt field and populate it in the normal way, which is then respected by the theme and formatted as a paragraph. If the administrator doesn’t create an excerpt, then the main post content is rendered in its place but truncated to a set number of characters, returned as a formatted paragraph with any incomplete words at the end of the string removed and then appended with an ellipsis. This is particularly useful if the design demands that the content is displayed in a grid or content box with a fixed and limited amount of space available.

PHP function to truncate the post content

Example usage inside the post loop

Example usage with a custom field

Article

LEAVE A COMMENT

Notify of
avatar
wpDiscuz