我在模板文件中使用<?php echo wp_trim_words(get_the_content(), 100); ?>
来控制要在页面上显示的单词数量,并在其下方有一个链接,用于将用户带到下一页以阅读整个内容但此功能会删除所有内容在预览页面上格式化内容。
我不能在这里使用wordpress默认摘录功能,因为它正在其他地方使用,我需要它的长度不同于此。有没有办法在使用时保留格式?
由于
我发现解决方案可能也可以帮助其他人。
function content_excerpt($excerpt_length = 5, $id = false, $echo = true) {
$text = '';
if($id) {
$the_post = & get_post( $my_id = $id );
$text = ($the_post->post_excerpt) ? $the_post->post_excerpt : $the_post->post_content;
} else {
global $post;
$text = ($post->post_excerpt) ? $post->post_excerpt : get_the_content('');
}
$text = strip_shortcodes( $text );
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
if ( count($words) > $excerpt_length ) {
array_pop($words);
$text = implode(' ', $words);
$text = $text . $excerpt_more;
} else {
$text = implode(' ', $words);
}
if($echo)
echo apply_filters('the_content', $text);
else
return $text;
}
function get_content_excerpt($excerpt_length = 5, $id = false, $echo = false) {
return content_excerpt($excerpt_length, $id, $echo);
}
// Call function in template file via
<?php content_excerpt(50); // 50 is amount to words ?>
答案 0 :(得分:0)
尝试:
echo apply_filters( 'the_content', wp_trim_words( get_the_content(), 100 ) );
答案 1 :(得分:0)
对于遇到类似问题的其他人,我直接从核心中取出默认的wp_trim_words()
函数,并将其更改为不剥离标记:
function wp_trim_words_retain_formatting( $text, $num_words = 55, $more = null ) {
if ( null === $more )
$more = __( '…' );
$original_text = $text;
/* translators: If your word count is based on single characters (East Asian characters),
enter 'characters'. Otherwise, enter 'words'. Do not translate into your own language. */
if ( 'characters' == _x( 'words', 'word count: words or characters?' ) && preg_match( '/^utf\-?8$/i', get_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 );
}
/**
* 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 );
}