Arrange Posts By Date In Order Of Closest To The Current Date

I have a list of events on a clients website that show in a sidebar. When viewing the homepage you see one event and if you’re anywhere else on the site you see two events in the sidebar. I am currently ordering them by using a meta_query compare that checks if the event is today or in the future.

What I would like to do is have the events show by closest to the current date first, then proceed up the chain until it finds one. Currently it appears to show events by furthest into the future instead. So if I have an event January 27th, 2012 and an event August 15th, 2012 it seems to show the August event.

Read More

The code I currently have is the following. I’d appreciate some advice on how to tweak it to get it to work the way I want. Please provide a little explanation with any code you post if possible, I’d like this to be a learning experience.

$totalPosts = 2;

    $args = array(
        'post_type'        => 'upcoming_courses',
        'order'            => 'ASC',
        'orderby'          => 'meta_value',
        'suppress_filters' => true,
        'posts_per_page'   => $totalPosts,
        'numberposts'      => $totalPosts,
        'meta_query' => array(
          array(
            'key' => 'course_date',
            'value' => date('Y-m-d'),
            'compare' => '>=',
            'type' => 'NUMERIC'
          )
        )
    );

    $my_query  = new WP_Query( $args );

Related posts

Leave a Reply

2 comments

  1. I know this is old, but ordering by DESC does not make sense for this case.

    You select DATEs >= CURRENT_DATE, now you want to display first the one closest to today, let’s say tomorrow and then day after tomorrow…

    What is greater date? Tomorrow or day after tomorrow? I don’t know about you, but I would bet that tomorrow < day after tomorrow, therefore, ordering DESC would mean you would first get day after tomorrow, because it is greater.

    I think your real problem is your typing (I assume you store your dates in Y-m-d format too…

    Tell WP_Query: “I am working with DATEs”:

    1. Say the ordering should be done with typing to DATE

    'meta_type' => 'DATE',
    

    2. Say the comparsion should be done with typing to DATE

    'meta_query' => [
      [
        'key' => 'course_date',
        'value' => date('Y-m-d'),
        'compare' => '>=',
        'type' => 'DATE' //!important!
      ]
    ],
    

    …then simple:

    'orderby' => 'meta_value',
    'order' => 'ASC',
    

    …should work just fine 🙂