wp_trim_words

Trims text to a certain number of words.

Description

(string) wp_trim_words( (string) $text, (int) $num_words = 55, (null) $more = null ); 

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.

Returns (string)

Trimmed text.

Parameters (3)

0. $text (string)
Text to trim.
1. $num_words — Optional. (int) => 55
Number of words. Default 55.
2. $more — Optional. (null) => null
What to append if $text needs to be trimmed. Default …..

Usage

  1. if ( !function_exists( 'wp_trim_words' ) ) { 
  2. require_once ABSPATH . WPINC . '/formatting.php'; 
  3.  
  4. // Text to trim. 
  5. $text = ''; 
  6.  
  7. // Number of words. Default 55. 
  8. $num_words = 55; 
  9.  
  10. // Optional. What to append if $text needs to be trimmed. Default '…'. 
  11. $more = null; 
  12.  
  13. // NOTICE! Understand what this does before running. 
  14. $result = wp_trim_words($text, $num_words, $more); 
  15.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/formatting.php  
  1. function wp_trim_words( $text, $num_words = 55, $more = null ) { 
  2. if ( null === $more ) { 
  3. $more = __( '…' ); 
  4.  
  5. $original_text = $text; 
  6. $text = wp_strip_all_tags( $text ); 
  7.  
  8. /** 
  9. * translators: If your word count is based on single characters (e.g. East Asian characters),  
  10. * enter 'characters_excluding_spaces' or 'characters_including_spaces'. Otherwise, enter 'words'. 
  11. * Do not translate into your own language. 
  12. */ 
  13. if ( strpos( _x( 'words', 'Word count type. Do not translate!' ), 'characters' ) === 0 && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) { 
  14. $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' ); 
  15. preg_match_all( '/./u', $text, $words_array ); 
  16. $words_array = array_slice( $words_array[0], 0, $num_words + 1 ); 
  17. $sep = ''; 
  18. } else { 
  19. $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY ); 
  20. $sep = ' '; 
  21.  
  22. if ( count( $words_array ) > $num_words ) { 
  23. array_pop( $words_array ); 
  24. $text = implode( $sep, $words_array ); 
  25. $text = $text . $more; 
  26. } else { 
  27. $text = implode( $sep, $words_array ); 
  28.  
  29. /** 
  30. * Filters the text content after words have been trimmed. 
  31. * @since 3.3.0 
  32. * @param string $text The trimmed text. 
  33. * @param int $num_words The number of words to trim the text to. Default 5. 
  34. * @param string $more An optional string to append to the end of the trimmed text, e.g. …. 
  35. * @param string $original_text The text before it was trimmed. 
  36. */ 
  37. return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );