WordPress: Limit Word Count of Post Excerpt or Content

Sometimes we’re not happy  how WordPress limit the lenght of our post excerpt or content. And by the help of some  codes online, we can set it’s length by the number of characters.

I’ve seen a lot of helpful code to limit the character of an excerpt in WordPress. But the output doesn’t look good. The word was cut into unreasonable length. I looked for a solution on how to limit an excerpt by words not by character. I already have a different approach on Limit the Number of Words/Character in WordPress Excerpt but I prefer the code below because I find it more usefull in different situation.

$string = get_the_content();
$trimmed = wp_trim_words( $string, $num_words = 20, $more = '... <a href="'.the_permalink().'">Read More</a>' );
$cleancontent = strip_shortcodes( $trimmed );
echo $cleancontent;

You can paste the code above inside the loop, replacing <?php the_excerpt(); ?>. Using this, it will show 20 words with a read more link at the end.

This code is actually useful in many situation. The value for line 1 is replacable by any string like Title or any other custom types.

*Some links may contain affiliate links. I may get small commission from your purchases to fund this website and to avoid annoying ads.