Support

Account

Home Forums General Issues Sorting posts by Date Picker field not working as expected

Helping

Sorting posts by Date Picker field not working as expected

  • I have created a custom Date Picker field for my posts and I am trying to generate a WP_Query to display the posts in ascending order by date(both month and year). However, I am not getting the expected result. Currently I have one post assigned with a November 2019 date, two with December 2019 and one with January 2020. Here is my loop:

    <?php
    
    $today = date('Ymd');
    
    $the_query = new WP_Query( array(
      'post_type'   => 'post',
      'post_status' => 'publish',
      'meta_query' => array(
        array(
          'key' => 'event_date',
          'value' => $today,
          'type' => 'DATE',
          'compare' => '>='
        )
      ),
      'meta_key' => 'event_date',
      'order_by' => 'meta_value_num',
      'order' => 'ASC',
      'posts_per_page' => -1
    ));
    
    # This will hold what group we're in
    $current_header = '';
    
    # The Loop
    while ( $the_query->have_posts() ) :
        $the_query->the_post();
    
        # get the datum for this post
        $date = strtotime(get_field('event_date'));
        $month = date('M', $date);
        $year = date('Y', $date);
    
        echo $month . ' ' . $year . '<h2>' . get_the_title() . '</h2>';
    
    endwhile;
    
    ?>

    However, the posts are being returned in this order:
    1. Nov 2019
    2. Jan 2020
    3. Dec 2019
    4. Dec 2019

    Any ideas as to why the January 2020 post is in the 2nd position instead of last?

  • Well, I realized the issue, supposed to be orderby instead of order_by. /facepalm

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.