Creating a Custom Excerpt in WordPress

WordPress has a lot of nice features out of the box, and one of those is the post excerpt. It works great for the most part, but what if you need two excerpts? Extravagant, I know, but say you need one excerpt for the blog archive and a shorter one for social media meta tags (you know, the OG metas).

Here’s a handy little function for creating an excerpt of a specified length:

// $text is the text to shorten, and $limit is the max number of words.
function limit_text($text, $limit) {
  $words = explode(' ', $text);
  if (count($words) > $limit) {
    $limited_words = array_slice($words, 0, $limit);
    $text = implode(' ', $limited_words) . '...';
  return $text;

It creates an array of words, chops it to the right length, then converts the array back to a string.

You can use that directly in your templates or wrap it in a shortcode or block and drop it in the editor. Boom.