国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > CMS > Wordpress > 正文

wordrpess the_excerpt()函數截取字符無效

2024-09-07 00:51:03
字體:
來源:轉載
供稿:網友

在一次開發中,我突然發現,the_excerpt函數無效了,不能顯示文章的摘要,我嘗試了多種可能的根源,仍然不解,為了不用query_posts就沒有問題,用query_posts之后就無效,為了解決這個問題,我翻閱了the_excerpt的源碼.具體代碼如下:

  1. /** 
  2.  * Display the post excerpt. 
  3.  * 
  4.  * @since 0.71 
  5.  * @uses apply_filters() Calls 'the_excerpt' hook on post excerpt. 
  6.  */ 
  7. function the_excerpt() { 
  8.         echo apply_filters('the_excerpt', get_the_excerpt()); 
  9.  
  10. /** 
  11.  * Retrieve the post excerpt. 
  12.  * 
  13.  * @since 0.71 
  14.  * 
  15.  * @param mixed $deprecated Not used. 
  16.  * @return string 
  17.  */ 
  18. function get_the_excerpt( $deprecated = '' ) { 
  19.         if ( !emptyempty$deprecated ) ) 
  20.                 _deprecated_argument( __FUNCTION__'2.3' ); 
  21.  
  22.         $post = get_post(); 
  23.  
  24.         if ( post_password_required() ) { 
  25.                 return __( 'There is no excerpt because this is a protected post.' ); 
  26.         } 
  27.  
  28.         return apply_filters( 'get_the_excerpt'$post->post_excerpt ); 

如果你仔細研究過,就會發現get_the_excerpt和the_excpert都是以抓取文章在數據庫中的post_excerpt字段來實現的,而當這個字段,也就是在后臺沒有填寫摘要時,為空,則會執行filter來調整和控制輸出的長度與內容.

如果你在開發中發現,怎么都不能讓the_excerpt顯示出原本的形式,你打算自己通過字符串截取等方法來代替這個函數的時候,不妨試試下面這段代碼:

  1. if(has_excerpt())the_excerpt();else
  2.  $length = apply_filters('excerpt_length',20); 
  3.  echo apply_filters('the_excerpt',wp_trim_words($post->post_content,$length)); 

看上去極其簡單的幾行代碼,卻包含了很多我們以往沒有接觸過的知識,首先,apply_filters的運用很少有人做到嫻熟,例如我們希望讓文章按照WordPress的輸出格式輸出時,我們可以使用:

echo apply_filters('the_content','你的HTML代碼')

來代替,這一招幾乎被90%的開發者忽略,甚至很多人根本不知道這種用法.

其次,wp_trim_words是最長被忽視的函數,我們老是希望截取一段特定字符串長度的文字,結果根本不知道WordPress早就準備好了這樣的函數出來.

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 淳化县| 卓尼县| 武乡县| 孟村| 临沂市| 巨鹿县| 郧西县| 嘉黎县| 松桃| 宜宾市| 都兰县| 津市市| 文化| 甘德县| 嘉定区| 中阳县| 津南区| 比如县| 扬中市| 沧州市| 肃北| 微山县| 澄城县| 大化| 龙游县| 竹溪县| 米林县| 峨眉山市| 贞丰县| 彰化县| 米脂县| 千阳县| 榆中县| 九寨沟县| 新邵县| 崇文区| 阿巴嘎旗| 什邡市| 米泉市| 石楼县| 泰来县|