展示你博客里评论最多的文章
May 16, 2009 # 8:44 pm # Wordpress 代码 # 2 Comments之前我曾写过如何给你的WordPress主题加上评论数目的文章,通过一个小小的技巧就可以吸引更多的读者发表评论。今天这篇文章可以说是上篇文章的续集。这篇文章将接受如何在wordpress博客里展示评论最多的文章。
首先,到控制后台找到header.php文件,在该文件内加上下面的代码:
<?php most_popular_posts($no_posts = 5, $before = ‘<li>’, $after = ‘</li>’, $show_pass_post = false, $duration=”) {
global $wpdb;
$request = “SELECT ID, post_title, COUNT($wpdb->comments.comment_post_ID) AS ‘comment_count’ FROM $wpdb->posts, $wpdb->comments”;
$request .= ” WHERE comment_approved = ’1′ AND $wpdb->posts.ID=$wpdb->comments.comment_post_ID AND post_status = ‘publish’”;
if(!$show_pass_post) $request .= ” AND post_password =””;
if($duration !=”") { $request .= ” AND DATE_SUB(CURDATE(),INTERVAL “.$duration.” DAY) < post_date “;
}
$request .= ” GROUP BY $wpdb->comments.comment_post_ID ORDER BY comment_count DESC LIMIT $no_posts”;
$posts = $wpdb->get_results($request);
$output = ”;
if ($posts) {
foreach ($posts as $post) {
$post_title = stripslashes($post->post_title);
$comment_count = $post->comment_count;
$permalink = get_permalink($post->ID);
$output .= $before . ‘<a href=”‘ . $permalink . ‘” title=”‘ . $post_title.’”>’ . $post_title . ‘</a> (‘ . $comment_count.’)’ . $after;
}
} else {
$output .= $before . “None found” . $after;
}
echo $output;
} ?>
要注意的一点就是上面这些代码必须放在</head>的前面。上面代码首行中的$no_posts = 5指的是你要显示文章的数目,你可以将他改为你想要的数目。
添加完这些代码之后,下面就要开始调用了。在你想要在主题里显示这些文章的地方添加上下面的代码,就大功告成了:
<?php most_popular_posts(); ?>
好了,赶紧去看看你的博客的效果吧。我知道还有一款插件也是可以实现该功能的,不过一时想不起来了,知道的朋友告知一下,我将在后面补上。
如果你还想看看更多的wordpress主题代码应用,看看这里!
Popularity: 4% [?]
Subscribe RSS
Comment RSS







Hello,
Everything dynamic and very positively!
Hi, outgoing posts there
thank’s concerning the interesting word