Enhance relatedPosts of ST
Simple Tags用于增强Wordpress目前薄弱的Tag管理以及相应的输出功能。介绍和具体功能可以查询官方网站。
我在使用st_related_posts函数时遇到两个问题:
1,对post_title不能限定字符。很多情况,尤其在侧边栏调用该函数时,需要对输出的日志题目进行字数限制,但目前即便最新版的Simple Tags(1.3.9)也没有这个功能。
2,对content限定字符的功能不适用中文。因为它按照英文习惯,对日志内容以空格为依据进行word数目统计。但中文文章基本只会在段落间才可能出现空格,所以输出的内容往往没有经过裁剪。
对问题1的解决方法如下:
找到插件中的simple-tags.php文件,找到function relatedPosts中:
- 'excerpt_wrap' => 55,
在下面加入
- 'excerpt_title' => 20,
$except_title为输出日志题目的限定字符数,默认20个。
继续往下找到
- $post_title = apply_filters( 'the_title', $result->post_title );
在下面加入
- if(ereg("[[:alnum:]][[:punct:]][[:space:]]", $post_title))//if string just include english letter,character and space
- {
- if(strlen($post_title)>$excerpt_title)
- {
- $post_title = substr($post_title,0,$excerpt_title);
- $post_title = utf8_trim($post_title);
- $post_title = $post_title.'.';
- }
- }
我在代码中加入了中英文标题的判断。因为绝大多数时候,中文比英文简练,一个日志的英文题目超出长度的概率比一个中文题目要大的多。所以对只含有英文(包括数字、字符)的题目进行字符限定。
保存以后,在theme中调用st_related_posts的参数中加入”&excerpt_tilte=?”,将”?”替换为你想要的数字即可。
对问题2的解决方法如下:
在function getExcerptPost中,找到
- $words = explode(' ', $content, $excerpt_length + 1);
- if ( strlen($words) > $excerpt_length ) {
注释掉两句,或者直接删除。
在其后增加
- if ( strlen($content) > $excerpt_length ) {
- $words=substr($content,0,$excerpt_length);
- $words = utf8_trim($words);
- $content = $words.'...';
修正以 空格为单位统计词语数目 为 直接统计字符数目。
注释以下部分:
- array_pop($words);
- array_push($words, '[...]');
- $content = implode(' ', $words);
utf8_trim用于去掉$content尾部可能出现的乱码。如果还没有安装中文wordpress工具箱,需要在simple-tags.php尾部加入:
- 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);
- }
切记,如果你已经使用中文wordpress工具箱,请略过增加function utf8_trim这一段,否则将出现插件冲突。
如果有其他的问题,可以给我留言。
This post is about enhancing the st_relatedd_posts function of Simple Tags.
As relatedPosts in ST, we can not limit the characters of output post titles. And when limiting ouput post cotent length by parameter except_wrap, it’s not suitable cutting post in Chinese with space to count the word number.
I change some codes in function relatedPosts to deal with these two problems. If you get questions as a English reader, please leave me a comment following.
Popularity: 6% [?]

太专业了,我看不懂。。。。。