更新日期:2014-12-04

有時候我們沒有填寫文章摘要,所以必須要從文章的內容擷取一小段文字來替代。很多範例都使用 php 的函式 substr 來截字,對於英語系通常不會有問題,但對於像是中文語系,每個字都換算成3位元,如果混和英文在裡面,就有可能會把中文字截斷而出現亂碼。

wordpress 內建了截字函式 wp_trim_words,對於這個問題將會迎刃而解,可以多多利用。

用法

[code language=”php”]
$trimmed = wp_trim_words( $text, $num_words = 55, $more = null );
[/code]

參數

$text: 要擷取的文字內容。
$num_words: 要擷取多少個文字,中文一個字也算1,預設是55個字。
$more: 預設是 ‘…‘ ,可以自己改成more連結樣式。

範例

[code language=”php”]
$content = get_the_content();
$trimmed_content = wp_trim_words( $content, 40, ‘<a href="’. get_permalink() .’"> …Read More</a>’ );
echo $trimmed_content;
[/code]