使用 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 ); // 文章标题
?>

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

默认用法:

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

参数:

  • $text

    (字符串) (必需) 要截取的内容默认: 无

  • $num_words

    (整数) (可选) 限定的字数默认: 55

  • $more

    (字符串) (可选) 截取后加在尾部的字符默认: ‘&hellip;’

示例:

<?php
 
$content = get_the_content();
$trimmed_content = wp_trim_words( $content, 40, '<a href="'. get_permalink() .'"> ...阅读更多</a>' );
echo $trimmed_content;
 
?>
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容