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

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

When you're saving the data on your custom post type you need to set it so that the meta box value is actually stored as a UNIX timestamp, eg:

if(!isset($_POST["event_informations_date"])) {
    return $post;
} else {
    $event_as_timestamp = strtotime ( $_POST["event_informations_date"];
    update_post_meta($post->ID, "event_informations_date", $event_as_timestamp );

This way you will have an orderable value for your meta keys. And you can query as per @helgatheviking

$args = array( 'post_type' => 'Event',
           'posts_per_page' => 1000,
           'order_by' => 'meta_value_num',
            'meta_value' => 'event_informations_date'  );

You will need to make sure that the add_meta_box() function you're using converts the UNIX timestamp from saved custom field values back to the format you need.

  • nice, i knew that was the missing piece. – helgatheviking Feb 23 '12 at 19:20

first you'll need to add more parameters

$args = array( 'post_type' => 'Event',
               'posts_per_page' => 1000,
               'order_by' => 'meta_value_num',
                'meta_value' => 'event_informations_date'  );

the problem will be that you can't really sort by your string date. i'd use 'meta_value' but b/c you have dd/mm/yy you're basically looking at all events on the first of the month being grouped together followed by those that start with 2, etc. i think you'll need to change the way your date is stored so that you'll be able to sort by it. maybe a unix timestamp?

ps- if you want all posts, i think you should change posts_per_page to -1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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