wp_query by meta key

I’ve written this loop to pull in posts that get the most views within the last 30 days (logging the view count to the DB as a custom meta key).

Though, upon thinking about it a little more I’m not really sure if I’m going about it the ‘right’ way, or at least the most logical way.

Read More
<?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; ?>

So, as you can see I’m limiting the date range to 30 days, ordering the posts by the meta_value_num and getting 33 posts.

So, logically what’s happening is any post published within the last 30 days will be displayed here in order of how many views they’ve had.
What got me thinking about it is when I created a page to pull the 33 most viewed posts from the last 7 days, they’re the same. Obviously.

So I think what I want to be doing is getting posts by how many views they’ve had IN the last 30 days/7 days, not posts published within those date ranges.

Am I thinking along the right lines? If so, can you give me any idea of how to go about that?

Related posts

Leave a Reply

2 comments

  1. If you’re running the WordPress 3.7 or later, you now can use date_query. Not tested, but your query will look something like:

    $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
          ),
        )
        )
    );