我有这个功能,可以显示 5 个观看次数最多的帖子。
在functions.php中我有:
// function to display number of posts.
function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0 View";
}
return $count.' Views';
}
// function to count views.
function setPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
目前我正在使用query_posts方法来显示 5 个观看次数最多的帖子:
<?php
query_posts( array (
'post_type' => 'post',
'showposts' => 5,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
)
);
if (have_posts()) : while (have_posts()) : the_post();?>
<a href="<?php the_permalink();?>"><?php the_title();?></a>
<?php endwhile; endif; wp_reset_query(); ?>
现在我正在尝试通过使用 wp_query 来获得相同的结果,但它似乎不起作用。
这是我用于wp_query的代码:
<?php $custom_query = new WP_Query('showposts=5, meta_key=post_views_count, orderby=meta_value_num'); // exclude category 9
while($custom_query->have_posts()) : $custom_query->the_post(); ?>
<a href="<?php the_permalink();?>"><?php the_title();?></a>
<?php endwhile; ?>
<?php wp_reset_postdata(); // reset the query ?>
它只显示 5 个最新帖子,而不是 5 个观看次数最多的帖子。有人可以帮我吗?