I have my site, which at the moment is display university open-days, at the moment they are sorting by order of page title, when actually I would prefer they sorted in order of date, soonest first, latest last.

Below is the code that i have so far and I cannot seem to work out how to sort them in order of date, any help?

<?php query_posts('post_type=page&post_parent=2&posts_per_page=-1&orderby=title&order=ASC'); ?>
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>

<!-- Calender Items -->

<?php $key = 'next_open_day'; $themeta = get_post_meta($post->ID, $key, TRUE); if($themeta != '') { 

echo '<div class="calender-item">';
echo '<h2>';
echo '<a href="';
echo '">';
echo '</a>';
echo '</h2>';
echo '<p>';
echo '</p>';
echo '<p>';
echo '</p>';
echo '<a target="_blank" href="';
echo '">';
echo 'Visit Website';
echo '</a>';
echo '</div>';

} ?>    


<?php endwhile; ?>
<?php wp_reset_query(); ?>

&orderby=date will return posts by their dates.

<?php query_posts('post_type=page&post_parent=2&posts_per_page=-1&orderby=date&order=ASC'); ?>

Replace first line with this to show post according to their date.

Reference - Passing variables to query_posts

Update -

To sort the posts as per custom field value, Here's the new code.

   query_posts('post_type=post&posts_per_page=-1&orderby=meta_value&meta_key=next_open_day&order=ASC'); ?>

Note - The date should be saved in - YYYY-MM-DD format. However we can further convert that date into required format. E.g. -

$date = "2012/08/21"; 
list($y, $m, $d) = split('/', $date); 
$newdate = $d.'/'.$m.'/'.$y;
echo $newdate;
  • but that will be the date of the post, not the date of teh field 'next_open_day' - if that makes sense? – Owen O'Neill Aug 6 '12 at 13:27
  • hum, you should have mentioned this clearly in question. Any way I'll update my answer. – amit Aug 6 '12 at 13:32
  • how you are saving dates in custom field(date format). To be able to sort it we need the meta_value as datestamp. – amit Aug 6 '12 at 13:56
  • the date stamp is dd/mm/yy - theres a live link here: universitycompare.com/open-days - apologies for the confusion @Amit – Owen O'Neill Aug 6 '12 at 14:32
  • did you get my message? - still trying to sort this :( – Owen O'Neill Aug 7 '12 at 9:33

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.