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

本文主要讲解:如何自动截取文章内容文字来作为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>';}?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值