0

I'm currently building an event calendar on WordPress with a custom post type. I'm using custom fields for date, description, etc.

Now I want to sort the events by date.. So -->

January 3, 2012
January 10, 2012
Feburary 1, 2012
....

3 Answers 3

1

I've used Jared's approach several times successfully, although I agree that Stephen Harris' answer should also now work (but it's a more recent addition to WP_Query which wasn't available at the time I was building an events listing). Depending on the date format you are suing to store the date, you might also need to use something like the following to display the date properly (this is probably basic if you come from a PHP background, but it had me stumped for a while).

<?php 
$course_start_date = get_post_meta($post->ID, 'start_date', true);
$fixed_date = strtotime($course_start_date);
echo date('jS F, Y' , $fixed_date) ;
?> 
0

To use the WordPress API, you can use get_posts and specify orderby 'meta value' (where you specify the meta key to be the key of the associated date). Assuming your post type is called 'event' and the date custom field is called 'date':

$events=get_posts( 
array ( 'post_type' => 'event', 
'orderby' => 'meta_value', 
'meta_key' => 'date' ) );

Or using WP_Query...

$query = new WP_Query( 
array ( 'post_type' => 'event', 
'orderby' => 'meta_value', 
'meta_key' => 'date' ) );

The above will return all 'events', (past and future), so you may also wish to add a filter to get only future events. To do that, add the following entries into the above array:

'meta_value'=>'YYYY-MM-DD',
'meta_compare'=>'>='

(Assuming, that is, dates are stored in 'YYY-MM-DD' format. The above 'YYY-MM-DD' should be replaced with todays date in that format, e.g. '2012-01-16'.

0

I used this to sort posts by its meta key and value descending in a custom post type:

global $wpdb;
$query_str = "
SELECT wposts.* 
FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
WHERE wposts.ID = wpostmeta.post_id 
AND wpostmeta.meta_key = '_sr_post_rating' 
AND wposts.post_type = 'entry' 
ORDER BY wpostmeta.meta_value DESC
";
$entries = $wpdb->get_results( $query_str, OBJECT );

However, if you don't want to use $wpdb, see Stephen Harris' answer. It should work the same.

Hope it helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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