函数文档

wp_trim_words()

💡 云策文档标注

概述

wp_trim_words() 函数用于将文本修剪到指定数量的单词,支持本地化处理,针对东亚语言等按字符计数的语言,$num_words 参数会应用于字符数。函数返回修剪后的文本,并可附加自定义后缀。

关键要点

  • 函数接受三个参数:$text(必需,要修剪的文本)、$num_words(可选,单词数,默认55)、$more(可选,修剪后附加的字符串,默认本地化的省略号)。
  • 函数会先使用 wp_strip_all_tags() 去除所有 HTML 标签,然后根据语言环境(通过 wp_get_word_count_type() 和 blog_charset 选项)决定按单词或字符分割文本。
  • 如果文本长度超过 $num_words,则截断并附加 $more;否则返回完整文本。
  • 函数通过 apply_filters('wp_trim_words', ...) 提供过滤器,允许开发者修改修剪后的文本。
  • 相关函数包括 wp_get_word_count_type()、wp_strip_all_tags()、__()、apply_filters() 和 get_option()。

代码示例

$text = 'Some very long text';
$words = 20;
$more = ' […]';

$excerpt = wp_trim_words( $text, $words, $more );

注意事项

  • 函数是本地化的,对于东亚语言,$num_words 参数作用于字符数而非单词数。
  • 用户贡献笔记中提供了额外示例,如用于评论摘录或自定义分割函数,但核心功能应优先参考官方文档。

📄 原文内容

Trims text to a certain number of words.

Description

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.

Parameters

$textstringrequired
Text to trim.
$num_wordsintoptional
Number of words.

Default:55

$morestringoptional
What to append if $text needs to be trimmed. Default '…'.

Default:null

Return

string Trimmed text.

Source

function wp_trim_words( $text, $num_words = 55, $more = null ) {
	if ( null === $more ) {
		$more = __( '…' );
	}

	$original_text = $text;
	$text          = wp_strip_all_tags( $text );
	$num_words     = (int) $num_words;

	if ( str_starts_with( wp_get_word_count_type(), 'characters' ) && preg_match( '/^utf-?8$/i', get_option( 'blog_charset' ) ) ) {
		$text = trim( preg_replace( "/[nrt ]+/", ' ', $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( "/[nrt ]+/", $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 $original_text The text before it was trimmed.
	 */
	return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
}

Hooks

apply_filters( ‘wp_trim_words’, string $text, int $num_words, string $more, string $original_text )

Filters the text content after words have been trimmed.

Changelog

Version Description
3.3.0 Introduced.

User Contributed Notes

  1. Skip to note 9 content

    Example: display comment excerpt in a comments custom query.

    $args = array(
    	'number' => 3,
    );
    $comments_query = new WP_Comment_Query;
    $comments = $comments_query->query( $args );
    if ( $comments ) {
    	foreach ( $comments as $comment ) {
    		echo wp_trim_words( $comment->comment_content, 20, ' […]' );
    	}
    }

  2. Skip to note 10 content

    If for some reason you need the words that were trimmed, here’s a modified version of this function, to return the words before AND after in an array:

    if( ! function_exists( 'smyles_wp_split_words' ) ){
    	/**
    	 * Split a string based on word count
    	 *
    	 * This is similar to WordPress wp_trim_words function, but instead of just trimming after a certain amount of
    	 * words, this function returns an array with 'before' and 'after' keys -- providing you the string of text up
    	 * to the number of words (in before key), and the words after (in the after key).  After key will be empty string
    	 * if there are less words in the passed string than number of words to split on.
    	 *
    	 *
    	 * @param string    $text
    	 * @param int       $num_words
    	 *
    	 * @return array    Array with `before` and `after` keys. The `before` key contains all words up to $num_words, the
    	 *                  `after` key contains the words after $num_words (or empty string if passed string has less words
    	 *                  than passed in $text)
    	 *
    	 */
    	function smyles_wp_split_words( $text, $num_words = 55 ) {
    		$text = wp_strip_all_tags( $text );
    		/*
    		 * translators: If your word count is based on single characters (e.g. East Asian characters),
    		 * enter 'characters_excluding_spaces' or 'characters_including_spaces'. Otherwise, enter 'words'.
    		 * Do not translate into your own language.
    		 */
    		if ( strpos( _x( 'words', 'Word count type. Do not translate!' ), 'characters' ) === 0 && preg_match( '/^utf-?8$/i', get_option( 'blog_charset' ) ) ) {
    			$text = trim( preg_replace( "/[nrt ]+/", ' ', $text ), ' ' );
    			preg_match_all( '/./u', $text, $words_array_matches );
    			$words_array = $words_array_matches[0];
    			$sep         = '';
    		} else {
    			$words_array = preg_split( "/[nrt ]+/", $text, -1, PREG_SPLIT_NO_EMPTY );
    			$sep         = ' ';
    		}
    		if ( count( $words_array ) > $num_words ) {
    			$before = implode( $sep, array_slice( $words_array, 0, $num_words ) );
    			$after  = implode( $sep, array_slice( $words_array, $num_words, count( $words_array ) - 1 ) );
    		} else {
    			$before = implode( $sep, $words_array );
    		}
    		$results = array(
    			'before' => $before,
    			'after' => isset( $after ) ? $after : ''
    		);
    		return $results;
    	}
    }

    https://gist.github.com/tripflex/5ccb97ac0b76d355bceff5111803d7ea