小冬SEO

wordpress调用文章描述摘要限制显示字符数量

2019-09-12 7:45:13 3233 WordPress笔记

wordpress调用文章描述摘要限制显示字符数量

<?php echo mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 60,"…"); ?>
<?php
echo wp_trim_words( get_the_content(), 100 ); // 文章内容,限制100个字符,溢出用...
echo wp_trim_words( get_the_excerpt(), 20 ); // 文章摘要,限制20个字符
echo wp_trim_words( get_the_title(), 10 ); // 文章标题,限制10个字符
?>

当我们在使用wordpress发文章的时候,如有必要显示文章的摘要,而且还要限制摘要的字数,这其实在wordpress系统中也定义好了,如果想自定义也是可以的,方法如下:

1、使用wordpress系统的摘要函数显示摘要:

<?php if(is_category() || is_archive() || is_home() ) {
    the_excerpt();
} else {
    the_content('Read the rest of this entry &raquo;');
} ?>
<div class="details"><div class="inside"><?php comments_popup_link('No Comments', '1 Comment', '% Comments'); ?> so far | <a href="<?php the_permalink() ?>">Read On &raquo;</a></div></div>

以上代码就可以显示摘要,如果你想直接替换掉

<?php the_content(); ?>

也是可以的。

2、如果你想全局控制摘要的显示字数,可以直接在function.php中添加以下代码即可:

function custom_excerpt_length($length){
    return 200;
}
add_filter('excerpt_length','custom_excerpt_lenght',999);

3、如果你不想全局调用,想针对每个页面局部调用摘要,可以用以下代码:

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

此代码比较灵活,还可以限制摘要字数为240。

4、当然你还可以在发布文章时使用自定义栏目添加摘要,需要结合以上方法事先自定义好变量,再到文章中调用即可。

版权保护: 本文由小冬SEO编辑发布,转载请保留链接: http://www.myseoyh.cn/shuo/121.html