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

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

<?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 $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;

?>

posted on 2021-10-26 09:09  剩余价值  阅读(116)  评论(0编辑  收藏  举报

导航