話說在制作WordPress主題的時候,我們通常要截取固定字數的文章標題,以保證主題樣式的某些需求。
牧澤使用的例子:
display: block;
讓a標簽變成塊
PHP:
<a href="<?php echo get_permalink( $prev_post->ID ); ?>">
上一篇: <br><?php echo $prev_post->post_title; ?>
</a>
CSS:
/*控制標題顯示*/
.post-PrevNext a{
display: block;
width:auto; /* 限制寬度(可選) */
white-space:nowrap; /* 禁止自動換行 */
overflow:hidden; /* 隱藏溢出的內容 */
text-overflow:ellipsis; /* 溢出文本使用...代替 */
padding: 1em 2em 1em 2em;
}
來源于:
https://www.wpdaxue.com/wordpress-title-cut-function.html

下面,倡萌就和大家分享下WordPress自動截取文章標題字數的4種方法。
使用wp_trim_words()截取
WordPress 3.3 新增了一個?wp_trim_words()?函數,專門用來截取限定字數的內容,比如文章、摘要、標題等,使用方法請看:https://www.wpdaxue.com/wp_trim_words.html
通過原生函數截取
將下面的代碼添加到主題的 functions.php 文件:
function customTitle($limit) {$title = get_the_title($post->ID);if(strlen($title) > $limit) {$title = substr($title, 0, $limit) . '...';}
?
echo $title;
}
然后在輸出文章標題的地方,使用下面的代碼:
<?php customTitle(30); ?>
注:30為標題字數,請根據自己的需求修改。如果標題字數小于30,就顯示完整標題;如果字數大于30,就截取30個字符,末尾自定添加…
通過自定義函數截取
//標題截斷
function cut_str($src_str,$cut_length){$return_str='';$i=0;$n=0;$str_length=strlen($src_str);
while (($n<$cut_length) && ($i<=$str_length))
{$tmp_str=substr($src_str,$i,1);$ascnum=ord($tmp_str);
if ($ascnum>=224){$return_str=$return_str.substr($src_str,$i,3); $i=$i+3; $n=$n+2;}elseif ($ascnum>=192){$return_str=$return_str.substr($src_str,$i,2);$i=$i+2;$n=$n+2;}elseif ($ascnum>=65 && $ascnum<=90){$return_str=$return_str.substr($src_str,$i,1);$i=$i+1;$n=$n+2;}else {$return_str=$return_str.substr($src_str,$i,1);$i=$i+1;$n=$n+1;}}if ($i<$str_length){$return_str = $return_str . '...';}if (get_post_status() == 'private'){ $return_str = $return_str . '(private)';}return $return_str;};
將上面的代碼添加到主題的 functions.php 最后一個 ?> 的前面,然后在需要調用的地方添加下面的代碼即可:
<?php echo cut_str($post->post_title,80); ?>
可以修改上面的數字來設定長度。
通過CSS來“截取”
嚴格來說,這不是截取,而是隱藏了溢出的字符。對標題所在的選擇器 id 或 class 添加下面的樣式:
.post-title{
?
width:250px; /* 限制寬度(可選) */
?
white-space:nowrap; /* 禁止自動換行 */
?
overflow:hidden; /* 隱藏溢出的內容 */
?
text-overflow:ellipsis; /* 溢出文本使用...代替 */
?
}