Rarst, a reader who blogs at www.rarst.net, asked me “How to get something like list of X posts with most comments in last Y days?”
After some research, I’m happy to provide a code to answer Rarst question.
Rarst, a reader who blogs at www.rarst.net, asked me “How to get something like list of X posts with most comments in last Y days?”
After some research, I’m happy to provide a code to answer Rarst question.
To achieve this hack, we have to make a custom SQL query by using the $wpdb object. Let's start by creating 3 php variables: The first one is the number of days between today and X days ago, the second is today's date and the last one is today's date - X days.
<?php
$days = 7; //To fetch posts published during the last 7 days
$today = date("Y-m-d H:i:s"); //Today's date
$daysago = date("Y-m-d H:i:s",strtotime(date('Y-m-j H:i:s')) - (7 * 24 * 60 * 60)); //Today - $days
$result = $wpdb->get_results("SELECT comment_count,ID,post_title, post_date FROM $wpdb->posts WHERE post_date BETWEEN $daysago AND $today ORDER BY comment_count DESC LIMIT 0 , 10");
foreach ($result as $topten) {
$postid = $topten->ID;
$title = $topten->post_title;
$commentcount = $topten->comment_count;
if ($commentcount != 0) {
?>
<li><a href="<?php echo get_permalink($postid); ?>"><?php echo $title ?></a></li>
<?php }
}
?>
You can paste this code wherever you want, to get the 10 most commented posts from the last 7 days.
2 Responses
Code is fail..Loop Does not work in my blog, “spesical page and dinamic page” !
$days = 7; assignment goes where other?
Hi, i know now problem..
New code:
$result = $wpdb->get_results("SELECT comment_count,ID,post_title, post_date FROM $wpdb->posts WHERE post_date BETWEEN '$daysago' AND '$today' ORDER BY comment_count DESC LIMIT 0 , 10");Trackbacks: