首先在网站后台的wordpress模板函数functions.php文件中加入以下的代码:
/*显示文章浏览次数*/
function getPostViews($postID){
$count = get_post_meta($postID,'views', true);
if($count==''){
delete_post_meta($postID,'views');
add_post_meta($postID,'views', '0');
return "0";
}
return $count.'';
}
function setPostViews($postID) {
$count = get_post_meta($postID,'views', true);
if($count==''){
$count = 0;
delete_post_meta($postID,'views');
add_post_meta($postID,'views', '0');
}else{
$count++;
update_post_meta($postID,'views', $count);
}
}
在需要显示浏览量的地方,包括首页,分类页,文章页都可以使用。
<?php setPostViews(get_the_ID()); echo number_format(getPostViews(get_the_ID())); ?>
WordPress网站制作热门文章排行榜(浏览量排序)
在需要调用按浏览量排序的热门文章位置,使用以下的代码进行调用文章列表;
<ul>
<?php $args=array(
'meta_key' => 'views',
'orderby' => 'meta_value_num',
'posts_per_page'=>6,
'order' => 'DESC'
);
query_posts($args); while (have_posts()) : the_post();?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><span class="kc-view fright">浏览:<?php setPostViews(get_the_ID()); echo number_format(getPostViews(get_the_ID())); ?></span></li>
<?php endwhile;wp_reset_query();?>
</ul>
这样就可以调用出用户浏览最多的6篇文章了。
按浏览量排序:使用 meta_key => ‘views’ 和 orderby => ‘meta_value_num’
备用方案:如果按浏览量查询无结果,自动切换到按日期排序
分类限制:只显示分类ID为6的文章
数量限制:显示6篇文章
版权声明:如发现本站有涉嫌抄袭侵权/违法违规的内容请联系客服!





