WordPress调用某段时间评论最多的文章

时间:2019-08-29   阅读:354

很多主题都用到了wordpress的热门文章函数,但一般都是调用建站以来所有时间评论最多的文章,说实在的,这个没什么意思,可能一直都是显示那几篇文章,今天给大家推荐一段代码,是调用WordPress某段时间内评论最多的文章。方法来自zwwooooo大师的 WordPress: 某段时间内最热文章。

1.之间将下面的代码放到主题的 functions.php 最后一个 ?> 的前面,注意看代码中的注释文字:

1
2
3
/* 某段时间内最热文章
 * Reference: http://www.boke.la/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
<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啦。

上一篇:WordPress调用最近更新过的文章

下一篇:WordPress添加友情链接页面(自动获取favicon.ico图标)

网友评论