很多主題都用到瞭wordpress的熱門文章函數,但一般都是調用建站以來所有時間評論最多的文章,說實在的,這個沒什麼意思,可能一直都是顯示那幾篇文章,今天給大傢推薦一段代碼,是調用WordPress某段時間內評論最多的文章。方法來自zwwooooo大師的 WordPress: 某段時間內最熱文章。
1.之間將下面的代碼放到主題的 functions.php 最後一個 ?> 的前面,註意看代碼中的註釋文字:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
/* 某段時間內最熱文章 * Reference: http://www.wprecipes.com/rarst-asked-how-to-get-most-commented-posts-of-the-week * Edit: zwwooooo */ function most_comm_posts($days=7, $nums=10) { //$days參數限制時間值,單位為‘天’,默認是7天;$nums是要顯示文章數量 global $wpdb; $today = date("Y-m-d H:i:s"); //獲取今天日期時間 $daysago = date( "Y-m-d H:i:s", strtotime($today) - ($days * 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 , $nums"); $output = ''; if(empty($result)) { $output = '<li>None data.</li>'; } else { foreach ($result as $topten) { $postid = $topten->ID; $title = $topten->post_title; $commentcount = $topten->comment_count; if ($commentcount != 0) { $output .= '<li><a href="'.get_permalink($postid).'" title="'.$title.'">'.$title.'</a> ('.$commentcount.')</li>'; } } } echo $output; } |
/* 某段時間內最熱文章
* Reference: http://www.wprecipes.com/rarst-asked-how-to-get-most-commented-posts-of-the-week
* Edit: zwwooooo
*/
function most_comm_posts($days=7, $nums=10) { //$days參數限制時間值,單位為‘天’,默認是7天;$nums是要顯示文章數量
global $wpdb;
$today = date("Y-m-d H:i:s"); //獲取今天日期時間
$daysago = date( "Y-m-d H:i:s", strtotime($today) – ($days * 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 , $nums");
$output = ”;
if(empty($result)) {
$output = ‘<li>None data.</li>’;
} else {
foreach ($result as $topten) {
$postid = $topten->ID;
$title = $topten->post_title;
$commentcount = $topten->comment_count;
if ($commentcount != 0) {
$output .= ‘<li><a href="’.get_permalink($postid).’" title="’.$title.’">’.$title.'</a> (‘.$commentcount.’)</li>’;
}
}
}
echo $output;
}
2.調用的時候,可以參考下面的樣例:
1 2 3 4 |
<h3>近期最熱文章</h3> <ul> <?php if(function_exists('most_comm_posts')) most_comm_posts(30, 10); ?> </ul> |
<h3>近期最熱文章</h3>
<ul>
<?php if(function_exists(‘most_comm_posts’)) most_comm_posts(30, 10); ?>
</ul>
PS:函數參數1是按天計算的,30就是30天;參數2是文章顯示數量,10就是顯示10篇,自己根據所需設置。具體的樣式就要靠自己寫css啦。