WordPress中自动截取限定字数的文章摘要

在WordPress模板制作的过程当中,我们经常需要截取限定字数的文章摘要.

有些朋友喜欢使用 more 标签来截取,还有一些朋友喜欢手动给每篇文章添加摘要,

然后使用 the_excerpt() 函数输出,但是这样耗时耗力,而且效果也不是特别好。

向大家介绍一个简单的方法:

1. 切换到主题所在目录,打开functions.php,加入如下代码:

<?php 
/*added by jacky*/
function jackyexcerpt($max_char = 200, $more_text = '...', $limit_type = 'content') {
 
    if ($limit_type == 'title') { $text = get_the_title(); }
    else { $text = get_the_content(); }
    $text = apply_filters('the_content', $text);
    $text = strip_tags(str_replace(']]>', ']]>', $text));
	$text = trim($text);
    if (strlen($text) > $max_char) {
		$text = substr($text, 0, $max_char+1);
        $text = utf8_conver($text);
		$text = str_replace(array("\r", "\n"), ' ', $text);
		$text .= $more_text;
		if ($limit_type == 'content'){
		$text = "<p>".$text."</p>";
        $text .= "<div class='read-more-wrapper'><a href='".get_permalink()."' title='read more' rel='nofollow'><span>阅读全文</span></a></div>";
		}
        echo $text;
    } else {
		if ($limit_type == 'content'){$text = "<p>".$text."</p>";}
        echo $text;
    }
}
 
function utf8_conver($str) {
	$len = strlen($str);
	for ($i=strlen($str)-1; $i>=0; $i-=1){
		$hex .= ' '.ord($str[$i]);
		$ch = ord($str[$i]);
	if (($ch & 128)==0) return(substr($str,0,$i));
		if (($ch & 192)==192) return(substr($str,0,$i));
	}
	return($str.$hex);
}
?>

2. 在需要显示摘要的地方使用下面的代码调用即可:

<?php jackyexcerpt(200);?>