Uffo
Uffo

Reputation: 10056

Order custom posts by a date metabox

I have a custom metabox, where I store the date in plain text like this: dd/mm/yyand now I need to order the posts by that date.The custom field is called event_informations_date

<?php
    $args = array( 'post_type' => 'Event','posts_per_page' => 1000 );
    $loop = new WP_Query( $args );
?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

Upvotes: 0

Views: 1670

Answers (3)

efoula
efoula

Reputation: 70

The solution is to order by meta_value_number

meta_key => 'event_informations_date',
orderby => 'meta_value_number',
order => 'DESC'

Upvotes: 0

Adam Pope
Adam Pope

Reputation: 3274

You'll want to add

meta_key => 'event_informations_date',
orderby => 'meta_value',
order => 'DESC'

However, because you are storing as plain text you will get a lexicographic ordering not a chronological ordering. So for example, you'll get

23/01/2012
22/02/2012
15/12/2011
10/05/2013

which is a random date order. I'm not sure whether you can overcome that unless you store the date as YYYY-MM-DD which lexicographically sorts in date order.

Upvotes: 2

Crinsane
Crinsane

Reputation: 818

First, save the date as a timestamp. then you can do the following in your WP_Query

$query = new WP_Query( 
           array ( 
              'orderby' => 'meta_value_num', 
              'meta_key'=> ' event_informations_date'
           )
         );

Upvotes: 0

Related Questions