You are here: Home » All Categories » WordPress » WP Trick » 简单的文章截断方法, 支持 Read more 加上 nofollow

简单的文章截断方法, 支持 Read more 加上 nofollow

Jun 23rd, 2010 21:54 | Leave a comment?(123) Go to comments

前几天的文章《闲来蛋疼: 把所有文章的more标签去掉了》里面谈到我把辛辛苦苦加上去的more标签又去掉了,做了这么蛋疼的事,很多盆友也发表了评论,其中 max 盆友在评论中说道:用  more 标签好处是灵活性高,如果有些只有两三百个字的文章就不需要用  more 标签,我一般也只在长文章才用  more 来截断。另外如果要用摘要的方式显示文章,不需要用插件,用 mb_strimwidth(strip_tags(apply_filters('the_content',  $post->post_content )), 0, 140, "......" ); 就行了,支援中文,缩略图可以另外处理,并没有影响。

今天在帮朋友修改主题时提到“不需要插件”实现文章截断,不需要显示图片、链接什么的,只要正确截断中文即可,于是我就想到了 max 所说的方法,在本地测试一翻,的确不错,而且可以为 read-more 加上 nofollow,又省了一个插件,非常好!

下面是方法

打开主题的 index.php / home.php /archive.php / ... 等文章列表页,找到类似

<?php the_content() ?> 或者 <?php the_excerpt() ?> 的删除掉,替换为下面的代码:

<p><?php echo mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 300,"..."); /* 300为字符数,注意这个要保持偶数,300即150个中文 */ ?></p>
<p class="read-more"><a href="<?php the_permalink(); ?>" rel="nofollow">Read more &raquo;</a></p>

PS: 如果你要显示图片,只要给strip_tags函数加个运行的图片标签<img>即可,即 strip_tags(apply_filters('the_content',  $post->post_content )) 变为 strip_tags(apply_filters('the_content',  $post->post_content ),"<img>"),但这样有个弊端,就是碰到刚好截断到图片链接就会出错,所以要先考虑自己文章的图片位置,要么靠前,要么靠后点

简单吧,真没想到这么简单就解决了,当然代码的执行效率不知道,喜欢的就折腾吧。

声明: 除非注明,ZWWoOoOo文章均为原创,转载请以链接形式标明本文地址
本文地址: http://zww.me/archives/25181

Filed under

WP Trick

| Tags:

,

Related Posts

Most Popular

123 Comments.

⊕Leave a comment?
  1. 宝宝健康成长 宝宝健康成长 Firefox 3.6.15Windows XP

    其实,很想求助zwwooooo 一个问题:我在当前theme首页采用mb_strimwidth 展示一部分post-content,但不兼容ie6,很是奇怪。有空能否帮我解惑下,先谢谢了。

    62楼

Leave a Reply