Php 如何在WordPress中显示浏览次数最多的帖子?

Php 如何在WordPress中显示浏览次数最多的帖子?,php,wordpress,filtering,customization,Php,Wordpress,Filtering,Customization,我想用WP_Query显示WordPress中浏览量最大的10篇文章,但我的代码没有显示任何内容 代码: 你能帮帮我吗 完整代码: <!-- Most Viewed --> <div class="home-post-wrapper col-sm-12 nopadding"> <?php $q_mostViewed = [ 'meta_key' => 'post_views_count',

我想用WP_Query显示WordPress中浏览量最大的10篇文章,但我的代码没有显示任何内容

代码:

你能帮帮我吗


完整代码:

<!-- Most Viewed -->

    <div class="home-post-wrapper col-sm-12 nopadding">

        <?php
        $q_mostViewed = [
            'meta_key' => 'post_views_count',
            'orderby' => 'meta_value_num',
            'order' => 'DESC',
            'posts_per_page' => '10'
        ];
        $mostViewed = new WP_Query($q_mostViewed);
        if ($mostViewed->have_posts()) :
            while ($mostViewed->have_posts()) :
                $mostViewed->the_post(); ?>
                  // Do things here
            <?php endwhile; 
        endif; ?>
    </div>

//在这里做事

打开激活主题的functions.php文件并添加以下代码

函数的作用是:使用post\u views\u count meta键添加或更新post元

/*
 * 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);
    }
}
single.php文件

从激活的主题目录打开single.php文件,并将setPostViews()函数放在循环中

setPostViews(get_the_ID());
显示浏览次数最多的帖子

下面的查询将根据post\u views\u count元键值获取post。将以下代码放在侧边栏或您希望显示最受欢迎帖子列表的位置

<?php
query_posts('meta_key=post_views_count&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();
?>


  • 你想显示在索引上还是另一个页面上?@IvanBarayev,在
    首页.php
    文件中,它将构建我的主页。Sweet,我将测试它,然后返回这里第一个代码不起作用,第二个代码可能起作用,但它基于评论而不是视图,不是吗?我在本教程中得到了它(如果你愿意的话):你可以用它,也可以用我的答案
    <?php
    query_posts('meta_key=post_views_count&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();
    ?>