Wordpress - 通过没有插件的视图获得 5 个热门帖子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12570746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Wordpress - get 5 popular posts by views without plugin
提问by Dimitri Badicean
Hi,
你好,
I have custom fields with image from posts, and I want to display the top 5 posts sorting by views. I am using WordPress, can you help me please?
我有来自帖子的图像的自定义字段,我想显示按视图排序的前 5 个帖子。我正在使用 WordPress,你能帮我吗?
Sorry for my bad English.
对不起,我的英语不好。
Thanks.
谢谢。
回答by AJ Zane
There's one error with Xhynk's reference:
Xhynk 的参考资料有一个错误:
The query it runs returns posts in alphabetical order (1, 2, 20, 23, 3, 4, etc)
它运行的查询按字母顺序返回帖子(1、2、20、23、3、4 等)
You just need to change
你只需要改变
'orderby' => 'wpb_post_views_count'
to
到
'orderby' => 'meta_value_num'
For the top 5, use:
对于前 5 名,请使用:
$popularpost = new WP_Query(array(
'posts_per_page' => 5,
'meta_key' => 'wpb_post_views_count',
'orderby' => 'meta_value_num',
'order' => 'DESC'
));
回答by Kabir Hossain
It is very easy. Just use this code into your functions.php
这很容易。只需将此代码用于您的functions.php
/*
* Set post views count using post meta
*/
function setPostViews($postID) {
$countKey = 'post_views_count';
$count = get_post_meta($postID, $countKey, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $countKey);
add_post_meta($postID, $countKey, '0');
}else{
$count++;
update_post_meta($postID, $countKey, $count);
}
}
put single.php
把single.php
setPostViews(get_the_ID());
This is your popular post query:
这是您的热门帖子查询:
<?php
query_posts('meta_key=post_views_count&posts_per_page=5&orderby=meta_value_num&
order=DESC');
if (have_posts()) : while (have_posts()) : the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title();
?></a>
</li>
<?php
endwhile; endif;
wp_reset_query();
?>
For details go
详情去
回答by Xhynk
Basically it's adding a meta field to each post - and deletes the old record when it's viewed, then replaces it with 'old record + 1'
基本上它是为每个帖子添加一个元字段 - 并在查看时删除旧记录,然后将其替换为“旧记录 + 1”