繁体   English   中英

通过元键wp_query

[英]wp_query by meta key

我编写了此循环,以获取过去30天内获得最多视图的帖子(将视图计数作为自定义元键记录到数据库中)。

但是,在仔细考虑之后,我不确定我是否会以“正确”的方式,或者至少是最合乎逻辑的方式进行操作。

<?php 

                // Create a new filtering function that will add our where clause to the query
                function filter_where( $where = '' ) {
                    // posts in the last 30 days
                    $where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
                    return $where;
                }

                add_filter( 'posts_where', 'filter_where' );

                    $popularpost = new WP_Query( array( 
                'posts_per_page' => 33, 
                'meta_key' => 'wpb_post_views_count', 
                'orderby' => 'meta_value_num', 
                'order' => 'DESC'  

                ) );


                remove_filter( 'posts_where', 'filter_where' ); ?>


                <?php if ( $popularpost->have_posts() ) : ?>



                <?php while ( $popularpost->have_posts() ) : $popularpost->the_post(); ?>

            <article <?php post_class('item-post block'); ?> id="post-<?php the_ID(); ?>">
                        <?php the_title (); ?>
            </article> <!-- end div post -->


                <?php endwhile; wp_reset_query(); ?>

                <?php endif; ?>

因此,如您所见,我将日期范围限制为30天,按meta_value_num排序帖子,并获得33个帖子。

因此,从逻辑上讲,最近30天内发布的任何帖子都将按照其拥有的观看次数在此显示。 让我思考的是,当我创建一个页面以拉近过去7天的33个最受欢迎的帖子时,它们是相同的。 明显。

因此,我认为我想做的是获取过去30天/ 7天内他们获得的观看次数,而不是在这些日期范围内发布的帖子。

我在沿着正确的方向思考吗? 如果是这样,您能给我任何想法吗?

如果您运行的是WordPress 3.7或更高版本,则现在可以使用date_query 未经测试,但您的查询将类似于:

$popularpost = new WP_Query( array(
    'posts_per_page' => 33,
    'meta_key' => 'wpb_post_views_count',
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
    'date_query' => array(
      array(
        'after' => '1 month ago',
        'column' => 'post_date_gmt', //posted within one month
      ),
    )
    )
);
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";

strtotime('30 days')=现在+ 30天

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM