WordPress 非插件侧栏带头像最新评论

通过使用最新评论插件WP-RecentComments可以很容易地实现 WordPress 博客侧边栏最新评论带avatar头像效果,但对于代码流博主来说,给 WP 添加多一个插件都是一种罪过,所以在有高人陆续研究出非插件WordPress的各种技巧,同样,侧栏最新评论带头像也可以使用“非插件”来搞定。

WordPress 非插件侧栏带头像最新评论:

在主题模板的functions.php模板添加以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function leonhere_new_comments($num,$name){
	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,comment_author_email, 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_author != '$name' AND comment_type = '' AND post_password = '' ORDER BY comment_date_gmt DESC LIMIT ".$num;
	$comments = $wpdb->get_results($sql);
	$output = $pre_HTML;
	$output .= "\n<ul class='comments'>";
	foreach ($comments as $comment) {
		$output .= "\n<li><div class='gavatar'>".get_avatar( $comment, 43,'',$comment->comment_author)."</div><div class='comments-con'><a href='".get_permalink($comment->ID)."#comment-" . $comment->comment_ID . "'>".strip_tags($comment->comment_author)."</a>".strip_tags($comment->com_excerpt) ."</div></li>";
	}
	$output .= "\n</ul>";
	$output .= $post_HTML;
	$output = convert_smilies($output);
	echo $output;
}

在sidebar.php文件添加调用代码:

1
<?php leonhere_new_comments(10,'');?>

括号里的单引号里输入管理员的用户名可以排除管理员的评论。

提醒:其中的CSS样式需要自己定义。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Grow your business fast with

Suku