wordpress內置函數(shù) the_excerpt() 是個使用頻率較高的函數(shù),它是用來獲取當前文章摘要的,以[…] 結尾,如果在文章中沒有編輯內容摘要字段,則默認截取文章的前55個字的內容,默認截取的字段去掉HTML標簽和圖形,并且一定要在循環(huán)內使用。
the_excerpt() 函數(shù)使用的方法也非常簡單,用法如下:
這個標簽沒有任何的參數(shù),直接使用即可,但函數(shù)默認的設置有時候并不能滿足用戶的需要,比如國內用戶以[…] 結尾就很不習慣,另外截取前 55 個字符有時候會太少了,還有文章摘要的結尾是不是我們可以自定義加個更多的鏈接呢,這些自定義只需要在主題 functions.php 文件中加入相應的代碼就可以了。
functions.php中的代碼
//設定摘要的長度
function new_excerpt_length($length) {
return 150;
}
add_filter('excerpt_length', 'new_excerpt_length');
//把摘要默認的結尾[...]
換成...
function new_excerpt_more(){
global $post;
return " <a href="". get_permalink($post->ID) . "">閱讀更多</a>";
}
add_filter('excerpt_more', 'new_excerpt_more');
//在頁面中直接調用摘要
<?php the_excerpt();?>
//也可以采用這種方法,但是測試的結果卻是摘要字符無法截斷,如果能截斷這個是比較完美的一個方法
<?php if(has_excerpt()){
the_excerpt();
} else{
echo mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 75, "…");
}?>
get_the_excerpt() 返回文章摘要賦值給變量