Sort Popular Posts by Views for the Last Week

I’m trying to sort the popular posts so it shows the most visited in the last week, but it hasn’t worked. Anyone have an idea of why it isn’t working?

<?php 

$popularpost = new WP_Query( array (

        'posts_per_page'      => 5,
        'ignore_sticky_posts' => 1,
        'meta_key'            => 'sw_post_views_count',
        'orderby'             => 'meta_value_num',
        'order'               => 'DESC',
        'date_query'          => array (
                array (
                        'year' => date( 'Y' ),
                        'week' => date( 'W' ),
                ),
        ),
) );

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

2 Answers
2

Use strtotime to compare dates.

$start = strtotime('yesterday');
$end = strtotime( '+1 week',$start);

$args = array(
    'posts_per_page' => 5,
    'ignore_sticky_posts' => 1,
    'meta_key' => 'sw_post_views_count',
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
    'date_query' => array(
        'after' => $end,
        'before' => $start,
    ),
);

$popularpost = new WP_Query( $args );

if ( $popularpost->have_posts() ) {

    while ( $popularpost->have_posts() ) {
        $popularpost->the_post();

        // Do your stuffs

    }

} 

Please note, this will return the posts from last 7 days, not last week.

Leave a Comment