wp_trim_words() 是 WordPress 3.3 版本新增的函式,該函式需要在 loop 迴圈中使用,透過該函式可以實現擷取限定字數的內容,比如擷取設定長度的文章內容、標題等,跟 mb_strings 函式實現的效果一樣。

程式碼結構:

<?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="'<span%20style="color: #339933;">. get_permalink() .'"> ...Read More</a>' ); echo $trimmed_content; ?>

例子:擷取設定字數標題

<?php $title = get_the_title(); $trimmed_title = wp_trim_words( $title, 20, '...' ); echo $trimmed_title; ?>