下面是一段自己改写的适用于wordpress标题和内容自动截断的代码。我一直不用wp内置的the_except或者<!--more—>的办法输出摘要,原因很简单,需要汉字无乱码,去html标签,另外还不需要自己动手插入截断位置。好处还有输出的整个模板页面比较整齐。

<?php

/* Auto-excerpt by winy */
function winyexcerpt($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='readmore'><a href='".get_permalink()."' title='查看全文点击此处' rel='nofollow'>继续阅读</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);
}

使用方法

在主题function.php里面插入上面的代码,在主题index.php或其它需要摘要输出的地方,找到<?php the_title(); ?>和<?php the_content(); ?>,以上分别用<?php winyexcerpt(60, '...', 'title'); ?>和<?php winyexcerpt(350); ?>替换。红字部分是截取字符数,后面两个参数分别是末尾省略符号和截取类别(标题或内容)。

完毕

评论分页: 1 2 3

发布评论

邮箱(必填)

换个背景