I came across a great way to limit the number of words displayed in the excerpt for a WordPress post, brought to you by the good folks at Cuppa (update – link removed because the site is gone). This method will allow you to choose a specific word limit every time you use the_excerpt or get_the_excerpt in your template files, making it extremely versatile and easy to use. You could even set the word count to a variable if you were so inclined, so you could change the count dynamically depending on your needs.
All you have to do is open up your functions.php file for your theme and enter the following code:
1 2 3 4 5 6 7 8 9 10 11 |
<?php function word_count($string, $limit) { $words = explode(' ', $string); return implode(' ', array_slice($words, 0, $limit)); } ?> |
The following code is then used to replace
1 |
<?php the_excerpt(); ?> |
or just to display anywhere you want this word-limited excerpt to appear.
1 |
<?php echo word_count(get_the_excerpt(), '30'); ?> |
You just replace 30 with the number of words you wish to limit the excerpt to. It’s quite simple! For more information, be sure to check out the original post.
7 Comments on “Limit Word Count in WordPress Excerpt”
hello
thanks for this solution
the issue now is that the “read more ” or “…” is no longer showing
is there a way i can add it
Are you sure it was displaying before you added this code? It shouldn’t be affected.
Please my concern might not be relevant to the topic but i recently discovered that my word count on my wordpress posts (title field) is beginning to count from 30. how do i overcome this please. thanks for a quick reply.
Great result!
Hi, this function works great, but how can i bring read more to see another part of the post.
I tried this and it worked but how to get … (3 dots) at the end of the excerpt? Please help…
Just replace “”
With “