Popular Post By Month in WordPress

I have been trying to get popular posts for the current month. I wrote the code given here. But showing nothing.

?php 
     $query_args = 
        array(
            'posts_per_page'  = 3,
            'post_type' = 'post',
            'date_query' = array(
                                array(
                                    'year' = date( 'Y' ),
                                    'month' = date( 'm' ),
                                ),
                            ),
            'meta_key' = 'wpb_post_views_count',
            'orderby' = 'meta_value_num',
            'order' = 'DESC',
        );

      $the_query = new WP_Query( $query_args );
        ?
    ?php 
    if ( $the_query-have_posts() ) :
    while ( $the_query-have_posts() ) : $the_query-the_post();

    ?
    div class="col-lg-4 col-md-4 col-sm-4 col-xs-12"
        div class="post-item"
            a class="post-thumb" href="?php echo get_the_permalink(); ?" title="?php the_title(); ?"
                ?php echo get_the_post_thumbnail();?
            /a

            h3
                a href="?php the_permalink(); ?" title="?php the_title(); ?"?php the_title(); ?/a
            /h3
        /div
    /div
    ?php endwhile; endif; ?

Topic popular-posts Wordpress

Category Web


I've tested your code on my installation and it is working just fine. So the code in not an issue.

There are two possible reasons why this is not showing any posts.

1) You do not have any posts for that month :)

2) You haven't any metadata 'wpb_post_views_count' in database so it returns nothing.

For debugging you can simply check if you have posts with current month published date.

If yes, then comment out 'meta_key' => 'wpb_post_views_count', and 'orderby' => 'meta_value_num', lines to check if any post is returned and see if missing metadata was causing this issue.

Cheers!

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.