0

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; ?>
  • "it does not work", is not an actual question. We can not do debugging for you without access to your server, or guess why you think there should be anything displayed. – Mark Kaplun Mar 8 '18 at 5:58
  • How do you update 'wpb_post_views_count' meta keys, because if this number is zero for all posts (or not set), you will not get any results? – Milan Petrovic Mar 8 '18 at 11:14
0

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!

  • Thanks for your answer and of course sorry for late reply. Yeah you are right. Nothing wrong with the code actually if I have metada as wpb_post_views_count. I removed wpb_ from the query and it worked fine. Thanks for your cooperation <3 – Fahad Mar 12 '18 at 9:33
  • Hey i am glad i have helped ;) Cheers! – Aleksandar Mitic Mar 12 '18 at 12:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.