wp_trim_words()自动截取字符串到一定长度,后面用...省略

目录

描述

自动截取 符串到一定长度,后面 ...省略。

wp_trim_words() 描述

用法

<?php $trimmed wp_trim_words$text$num_words 55$more null ); ?>

wp_trim_words() 用法

参数

$text

(string) (必填) 要修 的文本。

默认值: None

$num_words

(integer) (可选) 保留的单词个数。

 值: 55

$more

(string) (可选) 修剪  的文本后面跟的 符,默认  ...

默认值: '&hellip;

wp_trim_words() 参数

返回值

(string)

修剪之后的文本

wp_trim_words() 返回值

示例

An example which strips formatting:

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */

<?php
echo wp_trim_words( get_the_content(), 40, '...' );
?>

wp_trim_words() 示例

历史

  • 添加于 版本: 3.3.0

wp_trim_words() 历史

源文件

wp_trim_words() 函数的代码位于 wp-includes/formatting.php.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/**
 * 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.
 *
 * @since 3.3.0
 *
 * @param string $text      Text to trim.
 * @param int    $num_words Number of words. Default 55.
 * @param string $more      Optional. What to append if $text needs to be trimmed. Default '…'.
 * @return string Trimmed text.
 */
function wp_trim_words( $text, $num_words = 55, $more = null ) {
	if ( null === $more ) {
		$more = __( '…' );
	}

	$original_text = $text;
	$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( "/[

	 ]+/", ' ', $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( "/[

	 ]+/", $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 );
	}

	/**
	 * Filter 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 5.
	 * @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 );
}

wp_trim_words() 源文件

相关