雕刻时光

Typecho和WordPress的自动截断代码

之前用Typecho 搭建了一个站点,使用的是“芒果”主题,首页输出的是“文章标题”,而非内容,所以也就没有手动加more标签。后来换了主题之后,悲催的直接全文输出了。如果再一篇一篇的去添加more标签非得累死不可。再说手动加more标签由于字数的控制问题,会使截断的文章长短不一,影响整体美观。使用自动阶段代码省却了手工截断的烦恼,也可以输出的整个模板页面比较整齐。

WordPress自动截断代码一:

<?php echo mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 300,"..."); ?>

使用方法:用上面的代码替换当前主题archive.php、index.php模板文件中类似:<?php the_content(‘Read more…’); ?>或<?php the_excerpt(); ?>。其中数字200是字数,可以自行调整,但最好保持为偶数。

WordPress自动截断代码二:

<?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); ?>替换。截取字符数可自行修改,后面两个参数分别是末尾省略符号和截取类别(标题或内容)。【代码来源:winysky

Typecho自动截断代码:

<p><?php $this->excerpt(200, '...'); ?><a href="<?php $this->permalink() ?>" rel="bookmark" title="详细阅读关于<?php $this->title(); ?>">阅读全文...</a></p>

使用方法:在模版index.php文件中,用上面的代码替换掉<?php $this->content(); ?>。

15 thoughts on “Typecho和WordPress的自动截断代码”

  1. 感谢楼主 问题解决了 不过我看楼主的blog好像很久没更新了。。。

回复 哪里有羽绒被 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注