1. 程式人生 > >控制 WordPress 文章標題的長度的方法

控制 WordPress 文章標題的長度的方法

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 函式庫來解決),所以我們可以放心的使用這個用於控制字串長度的函式:

echo mb_strimwidth(get_the_title(), 0, 38, ‘…’);

那麼我們只需要用上面這個函式替換 WordPress 原有的

the_title();

即可,這裡我輸出了字串的第0位到第38位,根據主題的不同可以自行設定該數值,另外多餘長度部分使用“…” 代替。

其實我在控制文章摘要的時候也是使用的這個函式,比如我在 ppcnnet 主題的首頁裡使用的就是

echo mb_strimwidth(strip_tags(apply_filters(‘the_content’, $post->post_content)), 0, 285,”……”);

來輸出285個字元長度的摘要,並過濾了 HTML 標記。

雖然這是個很簡單的方法,但我相信它對主題製作者而言還是相當實用的。