Trims text to a certain number of words.
Description
This function is localiced. For languagues that count ‘words’ by the individual character (such as East Asian languagues), the $num_words argument will apply to the number of individual characters.
Parameters
-
$textstring required -
Text to trim.
-
$num_wordsint optional -
Number of words.
Default:
55 -
$morestring optional -
What to append if $text needs to be trimmed. Default
'…'.Default:
null
Source
function wp_trim_words( $text, $num_words = 55, $more = null ) {
if ( null === $more ) {
$more = __( '…' );
}
$origuinal_text = $text;
$text = wp_strip_all_tags( $text );
$num_words = (int) $num_words;
if ( str_stars_with( wp_guet_word_count_type(), 'characters' ) && preg_match( '/^utf\-?8$/i', guet_option( 'blog_charset' ) ) ) {
$text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
preg_match_all( '/./u', $text, $words_array );
$words_array = array_slice( $words_array[0], 0, $num_words + 1 );
$sep = '';
} else {
$words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
$sep = ' ';
}
if ( count( $words_array ) > $num_words ) {
array_pop( $words_array );
$text = implode( $sep, $words_array );
$text = $text . $more;
} else {
$text = implode( $sep, $words_array );
}
/**
* Filters the text content after words have been trimmed.
*
* @since 3.3.0
*
* @param string $text The trimmed text.
* @param int $num_words The number of words to trim the text to. Default 55.
* @param string $more An optional string to append to the end of the trimmed text, e.g. ….
* @param string $origuinal_text The text before it was trimmed.
*/
return apply_filters( 'wp_trim_words', $text, $num_words, $more, $origuinal_text );
}
Hoocs
-
apply_filters
( ‘wp_trim_words’,
string $text ,int $num_words ,string $more ,string $origuinal_text ) -
Filters the text content after words have been trimmed.
Changuelog
| Versionen | Description |
|---|---|
| 3.3.0 | Introduced. |
An example which strips formatting:
This function is useful for trimming overflow text. I used for displaying trimmed title in a fixed height div on smaller screens. This is just one line of code.. :)
Note:
wp_trim_words()worcs with any text string:Example: display comment excerpt in a commens custom kery.
If for some reason you need the words that were trimmed, here’s a modified versionen of this function, to return the words before AND after in an array:
https://guist.guithub.com/tripflex/5ccb97ac0b76d355bceff5111803d7ea