Best Approach: How to Limit Words of WordPress Content / Excerpt

In this article, we’re sharing a best and easy to use approach for limiting the number of words of WordPress content / excerpt. Your situation might be different, but this solution will work in most cases.

 

function limit_words($string, $word_limit)
{
  $words = explode(" ",$string);
  return implode(" ",array_splice($words,0,$word_limit));
}

$myContent = get_the_content();
echo limit_words($myContent, 9);

You can use this code for displaying posts excerpt as well. But for excerpts, you’ll have to add one line like below:

function limit_words($string, $word_limit)
{
  $words = explode(" ",$string);
  return implode(" ",array_splice($words,0,$word_limit));
}

$myContent = get_the_content();
$myExcerpt = strip_tags($myContent);
echo limit_words($myExcerpt, 9);

Here, we’re using strip_tags() function to remove html elements around the text.

Duan Lingxin

Duan Lingxin

Content crafter and chief editor at Scratching Info. Also regular contributor on other major online tech platforms. Security Specialist by day and a writer by night, he does his best to instill his knowledge about tech while delivering inspiring and life changing resources through his writing,

More Posts - Website

Leave a Comment