WordPress posts have two types of texts associated with them: the post’s content, and its excerpt. The content is the main part of the post, and the excerpt is either filled out in its own field or generated by WordPress by extracting the first part of the content.
In this article, we’ll concentrate on what happens if the post’s excerpt is empty, and how we can control the length of the generated excerpt. However, it’s always best to fill out the excerpt with your own words and thus gain the utmost control over that field. How to add excerpt in a WordPress post is described in the WPShout post:
How to Set a Custom Post Excerpt in WordPress
The Case for Requiring a Fixed Character Length Excerpt
Many sites’ homepages display a post list showing posts’ excerpts only. Sometimes that list’s design is that of a grid, where each post is a block in a row. In those cases, the space allotted to every post is very specific – with a specific width and height – so the length of each excerpt must be the same so that all blocks are neatly aligned by row and column.
WordPress has a good function called
the_excerpt() which displays a post’s excerpt. It works smartly: it first checks if there is an excerpt at all and if not, it extracts the first few words from the content. By default, it takes 55 words, but it is possible to change this number by using a filter, the
excerpt_length filter, which you can deep-dive into in this WPShout article.
Changing WordPress Excerpt Length: Learning Through Spelunking
Theoretically, we could use the
the_excerpt() function in our case where we want to limit the excerpt length. However, upon deeper inspection, it was not enough for us. Words are a very inaccurate unit of measure – words are of varying length, and we need something more precise: letters, or, as we call them in programming: characters. So this article will depict a function that takes the content (and not the excerpt) and extracts the desired number of characters from it.
This article will go through all parts of that function and explain all the elements that have to be taken into consideration in a function like this. Extracting characters doesn’t consist only of counting letters. The post might have other elements in it: HTML tags wrapping the words, images, shortcodes, blocks. Also, the counting of characters needs consideration for characters that are beyond ASCII code and extend to UTF-8. All of these issues will be discussed now.
The first thing we’ll want is to strip all HTML tags. This will also remove the
img tag and the comment tags that wrap Gutenberg blocks. Therefore it the first command in the function should be
$content = strip_tags($content);.
Now we’re left
This article was written by Lea Cohen and originally published on WPShout.