Handy, dandy WordPress excerpt length function

Written by: John | 22nd Jun 2015

If you have been using WordPress on multiple projects you must have come up against needing to pull a custom excerpt size?

Now there are many ways to do this, eg, you could use this to pull say 80 characters of copy:

//get the excerpt
$excerpt = get_the_excerpt();
//strip the html
$excerpt = strip_tags ($excerpt);
//return 80 chars
$excerpt = substr($excerpt, 0, 80);

But I found that WordPress already has a function built in to return a defined number of WORDS not CHARS. Now this is achievable using php string manipulation, but if there is a function already existing, why re-invent the wheel?

Here it is:

$excerpt = get_the_excerpt();
//simply return the first 10 words.
$excerpt = wp_trim_words( $excerpt, $num_words = 10, $more = '… ' );

How easy is that?

Related Posts

Code

Swipe close for mobile menu

Using Vanilla JS (ish) to add swipe features to mobile views.
Code

Full Width YouTube Videos

Make YouTube videos take the full width of an element while retaining the 16:9 ratio.
Code

CSS Transitions

Easy copy and paste transition css, to enable transitions to all properties.
Code

Command Line SSH stuff

Some tips and tricks for using the command line to do useful stuff, mainly just a reference for myself.
Code

Add a masonry blog to WordPress

Masonry post display So you have seen the fancy shmancy "Masonry blog" blog pages used on many modern WordPress sites and thought, that would look great on my site... Well here's how to add a masonry blog to WordPress without…