13 Mar
2009-04-02 ver0.2 Update: 支持”@用户名 “、”@用户名,”、”@用户名:”等多种形式;添加跳转链接为绝对路径,不再有分页跳转链接失效问题;链接添加类似“reply-回复的评论ID”的ID,便于使用JS实现一些特效。
在回复评论时我个人习惯使用如Twitter“@用户名 回复内容”的形式,不过由于不像Twitter能给用户名添加链接,如果评论较多的话读者并不能很轻易找到该用户的评论,手动添加又显得麻烦,当原评论被删除时还有链接失效的问题。
其实在Wordpress的插件库里你可以找到一个名为@reply的插件解决上述问题,它能自动给用户名添加链接,不过仔细看@reply的源代码你会发现每当它找到一个需要添加链接的用户名时就要进行一次数据库查询操作,相当浪费资源,同时它只对在评论起始处使用“@用户名”时才有效,多次或在评论内容中穿插使用都是无效的。此外@reply还有一个很大的BUG,当一个用户对一篇日志发布多次评论,你也多次使用“@用户名 ”的形式对该用户进行回复时,自动添加的链接指向的都是该用户最后发表的评论,这当然是不合理的。
于是我自己写了一个类似功能的函数,它不进行任何的数据库查询,无论“@用户名 ”在评论中什么位置使用多少次都是有效的,链接总是指向在该回复发表日期之前该用户发表的最近一篇评论。具体效果见这里,你可以拷贝后面的源代码或使用JKit Builder生成带此功能的插件。
/** * 自动替换评论中"@"为链接形式 * * 支持"@用户名 "、"@用户名,"、"@用户名:"等多种形式 * * @version 0.2 * @param array $comments * @return array */ function JKit_AtReply($comments) { global $JKit_AtReply_Foregoing_Comments; /** * JKit_AtReply中preg_replace_callback的回调函数 * * 查找之前的是否有找到用户名的评论,如果有则替换为链接形式,否则返回原值 * * @version 0.2 * @param array $matches * @return string */ function JKit_AtReply_Replace($matches) { global $JKit_AtReply_Foregoing_Comments; foreach ($JKit_AtReply_Foregoing_Comments as $comment) { if (strcasecmp($matches[1], $comment->comment_author) == 0) { $comment_link = get_comment_link($comment); return str_replace($matches[1], '<a id="reply-' . $comment->comment_ID . '" href="' . $comment_link . '">' . $comment->comment_author . '</a>', $matches[0]); } } return $matches[0]; } if (count($comments) <= 1) return $comments; $comments = array_reverse($comments); $count = 0; foreach ($comments as $comment) { $count++; $JKit_AtReply_Foregoing_Comments = array_slice($comments, $count); $comment->comment_content = preg_replace_callback("/@(.*?)[ ,:]/", 'JKit_AtReply_Replace', $comment->comment_content); } return array_reverse($comments); } add_filter('comments_array', 'JKit_AtReply');
NOTE: 添加的链接为页面内跳转,因此如果你对评论进行分页显示,链接可能无效,请自行修改代码。此外,必须保证在评论列表中每个评论有“comment-评论ID”的id,如id=”comment-5409″











2 Comments so far
很喜欢你的博客想和你做个友情连接!!
方便以后访问~~你的链接已经做好咯~~
网站名称:凡客诚品
网站地址:www.redcu.cn/
On the occasion of welcoming the Christmas season, Vietnam Hotel Network has launched its big discount promotion for tourists seeking for hotels in Hoi An, Nha Trang and Phu Quoc island in preparing for their relaxing new year vacations in Vietnam.
Leave a reply