I have some custom fields named ‘date’ and ‘start_time’ and would like to order the posts by my custom field of ‘date’ and then the ‘start_time’. I’ve got the following query – if anyone can point out where I’m going wrong that’d be great.
The query I have is below:
EDIT: The second array can be changed to anything – the field its self returns a value of anything between 0000 and 2359 – This is the value I need to sort by after the date
So I have my query returning this at the moment
Sun 26th May – Start Time: 0900
Sun 26th May – Start Time: 1300
Sun 26th May – Start Time: 2000
Sun 26th May – Start Time: 1030
But I’d like this:
Sun 26th May – Start Time: 0900
Sun 26th May – Start Time: 1030
Sun 26th May – Start Time: 1300
Sun 26th May – Start Time: 2000
$today = date("Ymd");
$args = array(
'post_type' => 'event',
'meta_query' => array(
array(
'key' => 'date',
'value' => $today,
'type' => 'numeric',
'compare' => '>'
),
array(
'key' => 'start_time',
'value' => array( 0, 2359 ),
'compare' => 'BETWEEN'
)
),
'orderby' => 'meta_value',
'meta_key' => 'date',
'order' => 'ASC',
'paged'=> $paged,
'posts_per_page'=> 12
);
UPDATE
I can get it to work using an sql query :
<?php
$querystr = "
SELECT wposts.*
FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta, $wpdb->postmeta wpostmeta2
WHERE wposts.ID = wpostmeta.post_id
AND wposts.ID = wpostmeta2.post_id
AND wpostmeta.meta_key = 'date'
AND wpostmeta2.meta_key = 'start_time'
AND wposts.post_type = 'event'
AND wposts.post_status = 'publish'
ORDER BY wpostmeta.meta_value ASC, wpostmeta2.meta_value ASC
";$pageposts = $wpdb->get_results($querystr, OBJECT);
?>
<?php if ($pageposts): ?>
<?php global $post; ?>
<?php foreach ($pageposts as $post): ?>
<?php setup_postdata($post); ?>
// STUFF
<?php endforeach; ?>
<?php endif; ?>
However, I can’t get it to only return posts where the date is greater than today.
Update 2:
Returning posts where date is greater than today was simple :
<?php
$today = date("Ymd");
$eventdate = get_field('date');
?>
<?php if($eventdate > $today) : ?>
A quick (and awkward) way would be to change your start_time custom field to be one long number that includes the date as well as the time:
And then, as indicated here:
I managed to solve it using a sql query – not ideal but it works
you can try by adding date(‘h:i:s’);