Skip to content

Instantly share code, notes, and snippets.

@schutzsmith
Created November 24, 2021 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schutzsmith/026df26511fab9364576ecf4d1e09afa to your computer and use it in GitHub Desktop.
Save schutzsmith/026df26511fab9364576ecf4d1e09afa to your computer and use it in GitHub Desktop.
WordPress query for a custom post type of "Events" that sorts by custom fields made in Advanced Custom Fields called "staart_date" and "start_time". I use two different fields because I wanted more control to do things like this.
<?php
return array(
'post_type' => 'events',
'posts_per_page' => '5',
'meta_key' => 'start_date',
'meta_query' => array(
'relation' => 'AND',
'date_clause' => array(
'key' => 'start_date',
'compare' => '=',
),
'time_clause' => array(
'key' => 'start_time',
'compare' => '=',
),
array(
'key' => 'start_date', // Check the start date field
'value' => date("Y-m-d"), // Set today's date (note the similar format)
'compare' => '>=', // Return the ones greater than today's date
'type' => 'DATE' // Let WordPress know we're working with date
),
),
'orderby' => array(
'date_clause' => 'ASC',
'time_clause' => 'ASC',
)
);
@shanomurphy
Copy link

You can do it with a single Date Time field:

'post_type' => 'event',
'meta_key' => 'event_start_datetime',
'orderby' => 'meta_value', // order by start date/time
'order' => 'ASC',

// Only retrieve future events
'meta_query' => array(
    array(
        'key' => 'event_end_datetime',
        'value' => date('Y-m-d H:i:s'),
        'compare' => '>=',
        'type' => 'DATETIME'
    )
)

@schutzsmith
Copy link
Author

Thanks @shanomurphy!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment