WordPress 侧边栏带头像的最新评论

谨以本文献给 Nox 童鞋。昨天 Nox 就问我怎么实现 WordPress 带头像的最新评论?因为当时正好在上班,电脑上没有 DW 和 notepad++ 这类软件,玩代码很不爽,又没有实力用 Windows 自带的记事本当场写出,所以就推荐了 zww 的成果:《带头像显示的最新评论代码 - 完善篇》,不过好像还是没有解决 Nox 的问题。现在也只有周末可以折腾折腾 WordPress 了,所以今天就拿自己的 WordPress 开刀,在侧边栏实现了带 gravatar 头像的最新评论。

先说说通用版:

<?php
global $wpdb;
$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved,comment_author_email, comment_type,comment_author_url, SUBSTRING(comment_content,1,25) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = '1' AND comment_type = '' AND comment_author != '万戈' AND post_password = '' ORDER BY comment_date_gmt DESC LIMIT 10";
$comments = $wpdb->get_results($sql);
$output = $pre_HTML;
foreach ($comments as $comment) {
$output .= "\n<li>".get_avatar(get_comment_author_email('comment_author_email'), 18). " <a href=\"" . get_permalink($comment->ID) . "#comment-" . $comment->comment_ID . "\" title=\"" . $comment->post_title . " 上的评论\">". strip_tags($comment->comment_author) .": ". strip_tags($comment->com_excerpt) ."</a></li>";
}
$output .= $post_HTML;
$output = convert_smilies($output);
echo $output;
?>

再说说 gravatar 头像缓存版的,大家各取所需啦:

<?php
global $wpdb;
$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved,comment_author_email, comment_type,comment_author_url, SUBSTRING(comment_content,1,25) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = '1' AND comment_type = '' AND comment_author != '万戈' AND post_password = '' ORDER BY comment_date_gmt DESC LIMIT 10";
$comments = $wpdb->get_results($sql);
$output = $pre_HTML;
foreach ($comments as $comment) {
$output .= "\n<li><img width=\"18\" height=\"18\" src=\"http://wange.im/gravatar/cache/avatar/".md5(strtolower($comment->comment_author_email)). " \" /><a href=\"" . get_permalink($comment->ID) . "#comment-" . $comment->comment_ID . "\" title=\"" . $comment->post_title . " 上的评论\">". strip_tags($comment->comment_author) .": ". strip_tags($comment->com_excerpt) ."</a></li>";
}
$output .= $post_HTML;
$output = convert_smilies($output);
echo $output;
?>

说明一下:代码中的“万戈”换成各自的名字就行,只是为了隐藏博主的最新留言,还有 gravatar 头像缓存的路径就根据各自的实际情况啦。

在完善 WordPress 带头像的最新评论的时候,最折腾我的就是样式,让我够累的,照顾了 Firefox,又忽略了 IE,特别是难缠的 IE6,我也是无能为力了,就先这么着吧,有时间再修改。