WordPress 隨機自定義摘要長度的教程
來源:程序員人生 發布時間:2014-02-06 17:44:23 閱讀次數:3160次
WordPress文章摘要的長度是默認的,你可以通過代碼修改讓它固定顯示地更長些或短些。通常摘要無法保證結尾剛好是一句話結束的地方,有時候一句話就被截斷了,如果讀者只看摘要,有可能會產生各種誤會。
如果將下面這段代碼貼入functions.php可以返回預先設定的最大長度,并刪除摘要內最后一句話后的其他內容,以保證摘要不在某個句子中間截斷。
要用到的是print_excerpt()函數。在主題模板下這個函數的用法是:
<?php print_excerpt(50); ?>
而下面這段代碼,將摘要的最大長度設為50個字符(你可以根據需要修改這個數值),然后截取50個字符內的所有完整句子作為摘要,最后一句話后的內容會被排除在摘要之外。
// 智能可變摘要長度
function print_excerpt($length) { // 摘要最大長度,以字符計算. Length is set in characters
global $post;
$text = $post->post_excerpt;
if ( '' == $text ) {
$text = get_the_content('');
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
}
$text = strip_shortcodes($text); // 可選,推薦使用
$text = strip_tags($text); // 使用 ' $text = strip_tags($text,'
<p><a>'); ' if you want to keep some tags</p>
<p> $text = substr($text,0,$length);
$excerpt = reverse_strrchr($text, '.', 1);
if( $excerpt ) {
echo apply_filters('the_excerpt',$excerpt);
} else {
echo apply_filters('the_excerpt',$text);
}
}</p>
<p>// 返回最后一個needle前的內容
function reverse_strrchr($haystack, $needle, $trail) {
return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) + $trail) : false;
}