标签: 留言

免插件实现WordPress侧边栏Recent Comments(最新评论)代码

秉承能少用插件,就不用插件的原则,完善Wordpress。如今可以无插件实现wordpress博客中侧边栏最新评论列表(Recent Comments),仅仅在sidebar.php中加以下代码即可。

<?php
global $wpdb;
$sql = “SELECT DISTINCT ID, post_title, post_password, comment_ID,
comment_post_ID, comment_author, comment_date_gmt, comment_approved,
comment_type,comment_author_url,
SUBSTRING(comment_content,1,30) 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
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>”.strip_tags($comment->comment_author)
.”:” . ” <a href=\”” . get_permalink($comment->ID) .
“#comment-” . $comment->comment_ID . “\” title=\”on ” .
$comment->post_title . “\”>” . strip_tags($comment->com_excerpt)
.”</a></li>”;
}
$output .= $post_HTML;
echo $output;?>
基本代码如此。当然,可以进一步对PHP代码做一些扩展,取得上佳的实现。
限制留言字数
SUBSTRING(comment_content,1,30)
其中“30”即留言字数限制。对于如何在结尾添加省略号,找到下面的foreach遍历那块,在或你想放的地方插入省略号就OK了。
限制留言条数
LIMIT 10″;
即输出限制为“10”条留言。
显示Gravatar头像
Gravatar头像是通过留言者邮件来判断显示的。所以先在$sql这块加上字段comment_author_email,形成:

$sql = “SELECT DISTINCT ID, post_title, post_password, comment_ID,
comment_post_ID, comment_author, comment_date_gmt, comment_approved,
comment_type,comment_author_url,comment_author_email

然后在foreach这块加上调用gravatar头像的代码, 形成类似:

foreach ($comments as $comment) {
$output .= “\n<li>”.get_avatar(get_comment_author_email(‘comment_author_email’), 32).strip_tags($comment->comment_author)
.”:” . ” <a href=\”” . get_permalink($comment->ID) .
“#comment-” . $comment->comment_ID . “\” title=\”on ” .
$comment->post_title . “\”>” . strip_tags($comment->com_excerpt)
.”</a></li>”;
}

排除管理员留言
管理员的留言比较多的话,会显得自己在小打小闹,有时一个最新评论列表里面就只看得到你一个人的留言,岂不是太孤芳自赏了。找到代码:

WHERE comment_approved = ‘1’ AND comment_type = ” AND
post_password = ‘

这些代码主要就限定你的留言列表中的每个条目所属的范围。比如comment_approved限定显示已通过审核的留言, comment_type限定留言的形式等等。而如果要排除admin,可以通过两种方式:
user_id=’0′
添加一个AND 把这句加到上面去,形成如:

WHERE comment_approved = ‘1’ AND comment_type = ” AND
post_password = ” AND user_id=”0″

留言列表里面就会显示访客也就是非注册用户的留言。对于大多数WordPress博客来说,这都是适用的。
comment_author != ‘admin’
留言作者不是admin,排除admin的留言。当然也适用于排除其它指定留言作者。需要注意的是,如果你这里排除的留言作者是中文名,要保证你的最新留言列表这个文件是UTF-8或ANSI as UTF-8编码。否则会无效。

当然还有一些排除的方法和其它的留言列表扩展应用,各位触类旁通。有兴趣的朋友可以对照着你的WordPress数据库表 wp_comments里面的各个字段,创建出你自己需要的留言列表,或者一些有趣的留言类应用。比如你可以弄一个列表只显示自己的回复,方便已留言且等待你回复的用户查看。