中文文章自动截取乱码或者不能截取的问题,相信很多使用WordPress的用户都遇到过这样的问题。相应的文章截取插件有很多,但是支持中文的很少很少,甚至找不到合适的。
最常见的文章截取插件是limit-post,这插件简单实用,可惜不支持中文。在中文下有的能截取,有的不截取。
此插件代码很简单,如下:
/* Plugin Name: Limit Posts Make: In file index.php replace the_content() with the_content_limit(1000, "more") */ function the_content_limit($max_char, $more_link_text = '(more...)', $stripteaser = 0, $more_file = '') { $content = get_the_content($more_link_text, $stripteaser, $more_file); $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); $content = strip_tags($content); if (strlen($_GET['p']) > 0) { echo ""; echo $content; echo ""; } else if ((strlen($content)>$max_char) && ($espacio = strpos($content, " ", $max_char ))) { $content = substr($content, 0, $espacio); $content = $content; echo ""; echo $content; echo "..."; echo ""; } else { echo ""; echo $content; echo ""; } } ?>
调用这个插件时在需要使用文章内容截取的地方将WordPres文章内容调用函数
改为limit-posts插件调用代码,数字“200”为显示的字数,“more”为截取内容后显示文字“more”
现在我们将此插件简单的改装下就可以支持中文截取了。代码如下:
/* Plugin Name: Limit Posts */ function the_content_limit($max_char, $more_link_text = '(more...)', $stripteaser = 0, $more_file = '') { $content = get_the_content($more_link_text, $stripteaser, $more_file); $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]>', $content); $content = strip_tags($content); if (strlen($_GET['p']) > 0) { echo ""; echo $content; echo ""; } else if ((strlen($content)>$max_char) && ($espacio = strpos($content, " ", $max_char ))) { $content = kc_substr($content, 0, $max_char); $content = $content; echo ""; echo $content; echo "..."; echo ""; } else { echo ""; echo $content = kc_substr($content, 0, $max_char); echo "..."; } } /* kc_substr */ function kc_substr($str,$from,$len){ preg_match_all('#(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+)#s',$str,$array, PREG_PATTERN_ORDER); $from1=0;$len1=0; foreach($array[0] as $key => $val){ $n=ord($val)>=128 ? 2:1; $from1+=$n; if($from1>$from){ $len1+=$n; if($len1<=$len){ $s.=$val; }else{ return $s; } } } return $s; } ?>
此代码简单改装后就支持中文截取,调用方法和limit-posts一样,使用函数:
改装后的插件支持中文和英文,好处就是DIY很自由想哪里调用截取,多少字数都行。当然这个代码还是有bug的,当调用字数多于280-300字的时候就会自动使用WordPress里面的“more”标签,所以字数最好不要超过260。一般最大调用250字足够了。当然这个代码只对会修改主题文件代码的朋友有用,新手就不用看了。
转自:http://bbs.wpgp.org/thread-6-1-1.html