wp_trim_words()
Trims text to a certain number of words.
This function is localized. For languages that count 'words' by the individual character (such as East Asian languages), the $num_words argument will apply to the number of individual characters.
Used By: wp_trim_excerpt()
Hooks from the function
Return
String
. Trimmed text.
Usage
wp_trim_words( $text, $num_words, $more );
- $text(string) (required)
- Text to trim.
- $num_words(int)
- Number of words.
Default: 55 - $more(string)
- What to append if $text needs to be trimmed.
Default: '…'
Examples
#1 Demo - cut text to 5 words
The example shows how the function works:
$text = '"Posner" - a weekly program by Vladimir Posner, which is broadcast since November 2008 on the nightly air of Channel One'; echo wp_trim_words( $text, 5, ' ...' ); // Output: // "Posner" is a weekly author's program ...
#2 Analog to the_excerpt()
Example, shows how to get the current post content and trim it down to 40 words and add a Read more...
link at the end, if needed:
$content = get_the_content(); $trimmed_content = wp_trim_words( $content, 40, sprintf( '<a href="%s"> ...Read More</a>', get_permalink() ) ); echo $trimmed_content;
Changelog
Since 3.3.0 | Introduced. |