如何使用 wp_trim_words() 截取限定字数的内容

田野里,高粱像喝醉了酒,频频点头;玉米正在变黄了的衣服里睡大觉;大豆也小坡了肚皮,蹦了出来;小白菜像列队的士兵整齐地排列在在菜地里。农民正忙忙碌碌地收获着一年的成果,田野里不时传出阵阵欢笑声。啊,秋天的景色真美啊!

WordPress 3.3 新增了一个 wp_trim_words() 函数,专门用来截取限定字数的内容,比如文章、摘要、标题等:

1
2
3
4
5
<?php
echo wp_trim_words( get_the_content(), 100 ); // 文章内容
echo wp_trim_words( get_the_excerpt(), 100 ); // 文章摘要
echo wp_trim_words( get_the_title(), 100 ); // 文章标题
?>

<?php echo wp_trim_words( get_the_content(), 100 ); // 文章内容 echo wp_trim_words( get_the_excerpt(), 100 ); // 文章摘要 echo wp_trim_words( get_the_title(), 100 ); // 文章标题 ?>

当然,这个函数默认需要在循环中使用。

默认用法:

1
<?php $trimmed = wp_trim_words( $text, $num_words = 55, $more = null ); ?>

<?php $trimmed = wp_trim_words( $text, $num_words = 55, $more = null ); ?>

参数:

  • $text

    (字符串) (必需) 要截取的内容

    默认: 无

  • $num_words

    (整数) (可选) 限定的字数

    默认: 55

  • $more

    (字符串) (可选) 截取后加在尾部的字符

    默认: '&hellip;'

示例:

1
2
3
4
5
6
7
<?php

$content = get_the_content();
$trimmed_content = wp_trim_words( $content, 40, '<a rel="nofollow noopener noreferrer" href="'. get_permalink() .'"> ...阅读更多</a>' );
echo $trimmed_content;

?>

<?php $content = get_the_content(); $trimmed_content = wp_trim_words( $content, 40, '<a rel="nofollow noopener noreferrer" href="'. get_permalink() .'"> ...阅读更多</a>' ); echo $trimmed_content; ?>

到此这篇关于如何使用 wp_trim_words() 截取限定字数的内容就介绍到这了。能遇见就珍惜,遇不见就努力。更多相关如何使用 wp_trim_words() 截取限定字数的内容内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!

您可能有感兴趣的文章
WordPress站点Gravatar头像前后台不显示的如何解决办法

WordPress做公司官网好吗?会不会显得档次很低?

WordPress主题需要支持https吗?WordPress站点如何如何实现https?

WordPress站点的页面/标签/分类URL地址如何添加.html?

WordPress站点更换了域名后数据库应该如何操作替换新旧域名?