首页 > 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. /** 
  12.  * Retrieve the post excerpt. 
  13.  * 
  14.  * @since 0.71 
  15.  * 
  16.  * @param mixed $deprecated Not used. 
  17.  * @return string 
  18.  */ 
  19. function get_the_excerpt( $deprecated = '' ) { 
  20.         if ( !emptyempty( $deprecated ) ) 
  21.                 _deprecated_argument( __FUNCTION__, '2.3' ); 
  22.  
  23.         $post = get_post(); 
  24.  
  25.         if ( post_password_required() ) { 
  26.                 return __( 'There is no excerpt because this is a protected post.' ); 
  27.         } 
  28.  
  29.         return apply_filters( 'get_the_excerpt', $post->post_excerpt ); 
  30. } 

如果你仔细研究过,就会发现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)); 
  4. } 

看上去极其简单的几行代码,却包含了很多我们以往没有接触过的知识,首先,apply_filters的运用很少有人做到娴熟,例如我们希望让文章按照WordPress的输出格式输出时,我们可以使用:

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

来代替,这一招几乎被90%的开发者忽略,甚至很多人根本不知道这种用法.

其次,wp_trim_words是最长被忽视的函数,我们老是希望截取一段特定字符串长度的文字,结果根本不知道WordPress早就准备好了这样的函数出来.

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表