好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

wordrpess the_excerpt()函数截取字符无效 - WordPress

wordrpess the_excerpt()函数截取字符无效

在一次开发中,我突然发现,the_excerpt函数无效了,不能显示文章的摘要,我尝试了多种可能的根源,仍然不解,为了不用query_posts就没有问题,用query_posts之后就无效,为了解决这个问题,我翻阅了the_excerpt的源码.具体代码如下:

/**    * Display the post excerpt.    *    * @since 0.71    * @uses apply_filters() Calls 'the_excerpt' hook on post excerpt.    */   function  the_excerpt() {           echo  apply_filters( 'the_excerpt' , get_the_excerpt());  }    /**    * Retrieve the post excerpt.    *    * @since 0.71    *    * @param mixed $deprecated Not used.    * @return string    */   function  get_the_excerpt(  $deprecated  =  ''  ) {           if  ( ! empty empty (  $deprecated  ) )                  _deprecated_argument(  __FUNCTION__ ,  '2.3'  );             $post  = get_post();             if  ( post_password_required() ) {                   return  __(  'There is no excerpt because this is a protected post.'  );          }             return  apply_filters(  'get_the_excerpt' ,  $post ->post_excerpt );  } 

如果你仔细研究过,就会发现get_the_excerpt和the_excpert都是以抓取文章在数据库中的post_excerpt字段来实现的,而当这个字段,也就是在后台没有填写摘要时,为空,则会执行filter来调整和控制输出的长度与内容.

如果你在开发中发现,怎么都不能让the_excerpt显示出原本的形式,你打算自己通过字符串截取等方法来代替这个函数的时候,不妨试试下面这段代码:

if (has_excerpt())the_excerpt(); else {    $length  = apply_filters( 'excerpt_length' ,20);    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早就准备好了这样的函数出来.

查看更多关于wordrpess the_excerpt()函数截取字符无效 - WordPress的详细内容...

  阅读:54次