WordPress theme hack – 自定义文章摘要显示和长度

WordPress有一个显示文章摘要的函数 the_excerpt(),这个函数可以用来显示博客文章的摘要内容,这个函数的需要使用在一个循环里面,例如下面的效果:

<?php if(have_posts()): ?>

<?php while(have_posts()) : the_post();?>

//...其他代码

<?php the_excerpt(''); ?>

//...其他代码

<?php endwhile; ?>

//...其他代码

the_excerpt()要用在展示文章的一个循环里面。Wordpress自带的功能只是去除了HTML相关标签内容,例如图片、连接等,但是显示的文章长度一点都厚道,有时候就是一整篇仅仅是去掉图片和格式的文章,看着何其蛋疼啊。下面就说说如何更好地显示文章摘要。

一、手动添加摘要

在编写文章的时候,文章编辑框下面会有个“摘要(Excerpt)”的框框,里面就是写摘要的地方了,填写你的摘要,然后,调用the_excerpt()的时候就会显示这里的内容了。只是需要手动添加,有点麻烦。

二、修改主题添加函数

上面说过,the_excerpt()函数主要的缺点就是生成的长度不够厚道,那么我们就把这个长度再缩短到适当的字数就好了。好了,函数奉上:

/**

* 截取文章摘要

*

*/

function utf8_trim($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 mul_excerpt ($excerpt) {

$myexcerpt = substr($excerpt,0,383);//此处为文章摘要的长度

return utf8_trim($myexcerpt) . '... ';

}

add_filter('the_excerpt',	'mul_excerpt');

将上面的代码复制到主题中的function.php的末尾,看看效果,是不是已经达到了你想要的长度呢?呵呵。

三、插件

这也是最简单的方法之一了,插件之多,多于牛毛,而且效果有些也很出众,例如带有缩略图的功能等,这里也不再叙述,请自行Google–Wordpress文章摘要插件

Wordpress at 2010, August 31, 11:56 pm, Tags: , , , ,
Trackback URL

One Comment on "WordPress theme hack – 自定义文章摘要显示和长度"

  1. K
    连裤袜
    September 4, 2010 at 14:56 Permalink

    挺实用的

Hi Stranger, leave a comment:

ALLOWED XHTML TAGS:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe to Comments