我使用下面的代码片段获取侧栏上每篇文章的视图数。php。一切都正常,但排序不正常。此外,它没有得到4个帖子,它只显示了1个帖子,虽然我已经写了\'numberposts\' => 4
.我想问题来自于后期查询。因为当我在主页上时,它会显示网站的最后一篇帖子,而不是我自定义的帖子类型。(例如,“你好,世界!”post)当我在归档页面中时,它会给出我自定义帖子类型的最后一篇帖子。有人能找到问题吗?谢谢
THE FUNCTION :
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\';
}
return $count;
}
// 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);
}
}
THE CODE I ADD TO SINGLE.PHP:
<?php setPostViews(get_the_ID()); ?>
THE CODE I USE AS POST QUERY TO GET AND SORT POSTS:
query_posts(array(
\'numberposts\' => 4, /* get 4 posts, or set -1 for all */
\'orderby\' => \'meta_value_num\', /* this will look at the meta_key you set below */
\'meta_key\' => \'post_views_count\',
\'order\' => \'DESC\',
\'post_type\' => array(\'news\',\'database\'),
\'post_status\' => \'publish\'
));
$myposts = get_posts( $args );
foreach( $myposts as $mypost ) { ?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php
}
wp_reset_query();
?>
最合适的回答,由SO网友:s_ha_dum 整理而成
你的代码没有意义。
您使用的query_posts()
, 您永远不应该这样做,但所做的只是对主查询进行重击。但是,您没有使用被破坏的查询然后使用get_posts()
使用未定义(就代码postedindicates而言)参数列表,因此它不会返回您期望的结果我想你要找的是:
$args = array(
\'posts_per_page\' => 4, /* get 4 posts, or set -1 for all */
\'orderby\' => \'meta_value_num\', /* this will look at the meta_key you set below */
\'meta_key\' => \'post_views_count\',
\'order\' => \'DESC\',
\'post_type\' => array(\'news\',\'database\'),
\'post_status\' => \'publish\'
);
$myposts = new WP_Query( $args );
if ($myposts->have_posts()) {
while ($myposts->have_posts()) {
$myposts->the_post(); ?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><?php
}
}