程序员人生 网站导航

WordPress 随机自定义摘要长度的教程

栏目:WordPress时间:2014-02-06 17:44:23

WordPress文章摘要的长度是默认的,你可以通过代码修改让它固定显示地更长些或短些。通常摘要无法保证结尾刚好是一句话结束的地方,有时候一句话就被截断了,如果读者只看摘要,有可能会产生各种误会。

如果将下面这段代码贴入functions.php可以返回预先设定的最大长度,并删除摘要内最后一句话后的其他内容,以保证摘要不在某个句子中间截断。

要用到的是print_excerpt()函数。在主题模板下这个函数的用法是:

<?php print_excerpt(50); ?>

而下面这段代码,将摘要的最大长度设为50个字符(你可以根据需要修改这个数值),然后截取50个字符内的所有完整句子作为摘要,最后一句话后的内容会被排除在摘要之外。

// 智能可变摘要长度
function print_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); // 可选,推荐使用
$text = strip_tags($text); // 使用 ' $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>// 返回最后一个needle前的内容
function reverse_strrchr($haystack, $needle, $trail) {
return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) + $trail) : false;
}
------分隔线----------------------------
------分隔线----------------------------

最新技术推荐