WordPress 基本自帶的函數都是直接輸出文章標題長度的,有些標題太長了就會自動換行,解決辦法一種是使用mbstring函數庫來解決,這樣就可以指定具體標題字數字節長度控制,另一種也可以通過CSS的方式控制,這裏我們只談使用函數來控制。
在 WordPress 裏,我們可以使用 the_title(); 來輸出文章標題,
與其相關的還有一個函數: get_the_title();
簡單的說說兩者的關系,get_the_title() 返回值是一個字符串(文章標題),而 the_title() 就是該字符串通過 echo 輸出後的值。
實際上就是 WordPress 自己在輸出文章標題時進行了簡化,直接用
the_title();
代替了
echo get_the_title();
除此之外這裏還需要用到另外一個函數:mb_strimwidth(string str, int start, int width, [string trimmarker], [string encoding]);mb_strimwidth() truncates string str to specified width. It returns truncated string.If trimmarker is set, trimmarker is appended to return value.start is start position offset. Number of characters from the beginning of string. (First character is 0)trimmarker is string that is added to the end of string when string is truncated.encoding is character encoding. If it is omitted, internal encoding is used.
現在大部分的 PHP 服務器都支持了 MB 庫(mbstring 庫 全稱是 Multi-Byte String 即各種語言都有自己的編碼,他們的字節數是不一樣的,目前php內部的編碼只支持ISO-8859-*, EUC-JP, UTF-8 其他的編碼的語言是沒辦法在 php 程序上正確顯示的。解決的方法就是通過 php 的 mbstring 函數庫來解決),所以我們可以放心的使用這個用於控制字符串長度的函數:
<?php echo mb_strimwidth(get_the_title(), 0, 35, '……'); ?>
那麽我們只需要用上面這個函數替換 WordPress 原有的
the_title();
即可,這裏我輸出了字符串的第 0 位到第 35 位,根據主題的不同可以自行設置該數值,另外多余長度部分使用 “…” 代替。
其實我在控制文章摘要的時候也是使用的這個函數,比如我在 ppcnnet 主題的首頁裏使用的就是
獲取文章部份內容
<?php echo mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 200,"……"); ?>
截取文章部份摘要
<?php echo mb_strimwidth(strip_tags(apply_filters('the_excerpt', $post->post_content)), 0, 200,"..."); ?>
讀取文章部分xx
<?php
echo wp_trim_words( get_the_content(), 200 ); // 文章内容
echo wp_trim_words( get_the_excerpt(), 200 ); // 文章摘要
echo wp_trim_words( get_the_title(), 200 ); // 文章標題
?>
這些函數默認需要在循環中使用。
默認用法:
<?php $trimmed = wp_trim_words( $text, $num_words = 55, $more = null ); ?>
參數:
$text
(字符串) (必需) 要截取的內容
默認: 無
$num_words
(整數) (可選) 限定的字數
默認: 55
$more
(字符串) (可選) 截取後加在尾部的字符
默認: ‘…’
示例:
<?php
$content = get_the_content();
$trimmed_content = wp_trim_words( $content, 200, '<a href="'. get_permalink() .'"> ...閱讀更多</a>' );
echo $trimmed_content;
?>
來輸出 200 個字符長度的摘要,並過濾了 HTML 標記。
雖然這是個很簡單的方法,但我相信它對主題制作者而言還是相當實用的。