按字符分类的简短内容

时间:2012-11-10 作者:Lea Cohen

Possible Duplicate:
excerpt in characters

在我们的一些网站中,我们需要显示帖子的摘录(内容管理员不输入摘录)
我们可以使用the_excerpt 函数,但从我所看到的,我只能控制它提取的单词的数量,这对我们来说有点太笼统了(一个单词可以有2个字母,或10个字母…)<因此,我们需要一个函数来获取字符数并从内容中提取该数量。但我们也不想让这些词被在中间。最后一个需要是该函数与php字符串函数的多字节版本协同工作(例如:usemb_substr 而不是substr)

是否有可执行此操作的WP内置功能?

1 个回复
SO网友:Lea Cohen

没有内置的WordPress函数可以按字符数修剪字符串。

/**  
* Get a limited part of the content - sans html tags and shortcodes -  
* according to the amount written in $limit. Make sure words aren\'t cut in the middle  
* @param int $limit - number of characters  
* @return string - the shortened content   
*/  
  function mop_the_short_content($limit) {  
     $content = get_the_content();  
     /* sometimes there are &lt;p&gt; tags that separate the words, and when the tags are removed,   
     * words from adjoining paragraphs stick together.    
     * so replace the end &lt;p&gt; tags with space, to ensure unstickinees of words */  
       $content = str_replace(\'&lt;/p&gt;\', \' \', $content);  
   $content = strip_tags($content);  
   $content = strip_shortcodes($content);  
   $ret = $content; /* if the limit is more than the length, this will be returned */  
   if (mb_strlen($content) &gt;= $limit) {  
      $ret = mb_substr($content, 0, $limit);  
      // make sure not to cut the words in the middle:  
      // 1. first check if the substring already ends with a space  
      if (mb_substr($ret, -1) !== \' \') {  
         // 2. If it doesn\'t, find the last space before the end of the string  
         $space_pos_in_substr = mb_strrpos($ret, \' \');  
         // 3. then find the next space after the end of the string(using the original string)  
         $space_pos_in_content = mb_strpos($content, \' \', $limit);  
         // 4. now compare the distance of each space position from the limit  
         if ($space_pos_in_content - $limit &lt;= $limit - $space_pos_in_substr) {  
            /* if the closest space is in the original string, take the substring from there*/  
            $ret = mb_substr($content, 0, $space_pos_in_content);  
         } else {  
            // else take the substring from the original string, but with the earlier (space) position   
            $ret = mb_substr($content, 0, $space_pos_in_substr);  
         }  
      }  
   }  
   return $ret . \'...\';  
}

结束

相关推荐

Pre_Get_Posts()操作中的多个orderby参数

引用@Otto\'s response 对于我提出的一个关于按多个字段排序的问题,他说:无法使用朴素的WP\\U查询。使用posts\\u orderby过滤器添加您自己的订购字符串。function my_order($orderby) { global $wpdb; return \"{$wpdb->posts.post_author} ASC, {$wpdb->posts.post_date} DESC\"; } add_filte