WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
share|improve this question

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).

$course_start_date = get_post_meta($post->ID, 'start_date', true);
$fixed_date = strtotime($course_start_date);
echo date('jS F, Y' , $fixed_date) ;
share|improve this answer

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':

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:


(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'.

share|improve this answer

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!

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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