Wordpress直接按字符数截断的发生的摘要必定不足友好,假如我们设定一个摘要的最大长度,可是又能不截断句子,这样应该会好许多吧。
第一步,将以下代码插手到主题文件夹中的functions.php
// Variable & intelligent excerpt length.function print_excerpt($length) { // Max excerpt length. Length is set in characters
global $post;
$text = $post->post_excerpt;
if ( '' == $text ) {
$text = get_the_content('');
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
}
$text = strip_shortcodes($text); // optional, recommended
$text = strip_tags($text); // use ' $text = strip_tags($text,'
<p><a>'); ' if you want to keep some tags</p>
<p> $text = substr($text,0,$length);
$excerpt = reverse_strrchr($text, '.', 1);
if( $excerpt ) {
echo apply_filters('the_excerpt',$excerpt);
} else {
echo apply_filters('the_excerpt',$text);
}
}</p>
<p>// Returns the portion of haystack which goes until the last occurrence of needle
function reverse_strrchr($haystack, $needle, $trail) {
return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) + $trail) : false;
}
第二步,在需要利用摘要处所插入
<?php print_excerpt(50); ?>个中,“50”可以修改为自界说的最大摘要长度。