清源绿里

中文wp中的the_content_rss调用问题

今天给朋友建立 wordpress 博客,优化模版时遇到这么一个问题。

该模版首页调用 the_content_rss 函数,并对输出内容大小进行限制。它是这么写的:the_content_rss(”,FALSE,”,50)。但是我发现 post 却是完全输出,并没有削去50个字符以后的内容。

几经折腾发现 the_content_rss 对内容大小限制的对象是 word。再具体一点说就是以空格为界将内容划分为很多的word,然后输出 the_content_rss 需要调用的数目。

问题在于,就英文来说空格的确能作为区分 word 的依据。但对中文来说,除了标点很少有人会在句子中夹杂空格。因此对于中文post,the_content_rss 几乎是输出全文的。

解决办法是修改 wordpress 系统目录下 wp-includes 文件夹里的 feed.php 包含的 the_content_rss 函数。为了不影响其他地方的调用。我们新建一个 the_chinesecontent_rss 。使用字符作为限制的对象,并再写utf8_trim函数清理中文字符截断可能产生的乱码。

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
function the_chinesecontent_rss($more_link_text='(more...)', $stripteaser=0, $more_file='', $cut = 0, $encode_html = 0) {

$content = get_the_content($more_link_text, $stripteaser, $more_file);
$content = apply_filters('the_content_rss', $content);

if ( $cut && !$encode_html )
      $encode_html = 2;
if ( 1== $encode_html ) {
      $content = wp_specialchars($content);
      $cut = 0;
}
elseif ( 0 == $encode_html ) {
      $content = make_url_footnote($content);
}
elseif ( 2 == $encode_html ) {
      $content = strip_tags($content);
}

if ( $cut ) {
      $excerpt =substr($content,0,$cut);
      $excerpt = utf8_trim($excerpt);
      $content = $excerpt.'...';
}
$content = str_replace(']]>', ']]>', $content);
echo $content;
}

function utf8_trim($str) {

    $len = strlen($str);

    for ($i=strlen($str)-1; $i>=0; $i-=1){
         $hex .= ' '.ord($str[$i]);
         $ch = ord($str[$i]);

    if (($ch & 128)==0) return(substr($str,0,$i));
    if (($ch & 192)==192) return(substr($str,0,$i));
    }
return($str.$hex);
}

下载该函数:

Download: the_chinesecontent_rss.php  the_chinesecontent_rss.php (1.1 KiB, 2,729 hits)

文章评论

  1. :)-辛苦啦~嘿嘿~

  2. 能做一个txt文件下载吗?我从上面拷贝下来以后再保存总是出错,自己又不懂代码,完全不知道哪里有问题。

  3. 搞定了,多谢提醒。

Leave a Comment