您的位置:首页 > 其它

WordPress如何自动截取文章内容作为首页摘要

2013-05-25 12:33 411 查看
本文主要讲解:如何自动截取文章内容文字来作为WordPress首页文章摘要,众所周知,WordPrss是带有摘要函数的,the_excerpt(),但我们之前却不常用到她,因为她不支持中文截取。现在好消息来了,她已经支持中文截断了。

手动添加摘要,在TinyMCE编辑器下有填写摘要的编辑框(默认下可能不显示,点击右上角显示选项即可),如何你的主题首页在使用the_excerpt(),在这里填写好摘要后,首页就会显示你填写的摘要。本文的重点是自动摘要,往下看。


mb_strimwidth()截取摘要

在此之前,the_excerpt()不支持中文截断字数,我们只能通过函数mb_strimwidth()截断the_content()来完成。

文章标题字数截断
<?php echo mb_strimwidth(get_the_title(), 0, 36,"..."); ?>


文章内容字数截断

将下列代码替换掉主页(index.php)归档页(archive.php)等等中的<?php the_content(); ?>即可。
<?php echo mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 280,"...",'utf-8'); ?>


说明:截取文章中280字节作为摘要。

文章评论字数截断
<?php echo mb_strimwidth(strip_tags($rc_comm->comment_content), 0, 36,"..."); ?>


the_excerpt()自动截取摘要

第一步:将下列代码替换掉主页(index.php)归档页(archive.php)等等中的<?php the_content(); ?>。
<?php the_excerpt(); ?>


第二步:修改主题模板函数function.php添加相应的功能函数。如下.

复制下列代码将其粘贴到主题functions.php闭合中:
//新摘要字数截断
function new_excerpt_length($length) {
return 280;
}
add_filter('excerpt_length', 'new_excerpt_length');
function new_excerpt_more($more) {
return '···';
}
add_filter('excerpt_more', 'new_excerpt_more');


说明:同样截取文章中280字节作为文章摘要


补充:侧边栏标题字数限定

下面是mb_strimwidth()限定标题字数的两个实例,不同函数方法不一样。

侧边栏随机文章标题字数限定
<?php $random = get_posts('orderby=rand&numberposts=10'); foreach($random as $post ) : ?>
<li><a href="<?php the_permalink(); ?>"><?php echo mb_strimwidth(strip_tags(apply_filters('the_title', $post -> post_title)), 0, 35, '...'); ?></a></li>
<?php endforeach; ?>


侧边栏最新评论标题字数限定
<?php $comments = get_comments('number=10'); foreach($comments as $comment){echo '
<li><em>'.get_comment_author().' - </em><a href="'.get_comment_link().'" rel="nofollow" title="'.get_comment_text().'">'.mb_strimwidth(get_comment_text(), 0, 28, '...').'</a></li>';}?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: