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 have three custom fields set for each of the posts in the events category — year, month, and day. I am already querying for the events category, and now I'd like to sort the posts by the custom fields. I assume that I just need to insert something into the query_posts section of the code, but I'm not sure what. Any suggestions?

<?php query_posts('category_name=events&showposts=6'); ?>
<?php while (have_posts()) : the_post(); ?>
        <div class="date">
            <span class="day"><?php echo get_post_meta($post->ID, 'month', true); ?>/<?php echo get_post_meta($post->ID, 'day', true); ?></span>
            <span class="year"><?php echo get_post_meta($post->ID, 'year', true); ?></span>
        <div class="details">
            <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> &rarr;</h3>
<?php endwhile; ?>

I can explain more: the date the post was created is unimportant, but I want to sort first by the "year" custom field, then by the "month" custom field, and then by the "day" custom field

share|improve this question

migrated from stackoverflow.com Jun 5 '12 at 22:15

This question came from our site for professional and enthusiast programmers.

I don't think there's an easy to sort by three different meta values, and really, I don't see why you need to in this case. Why not just save the event date in one meta value and sort by that? It makes your query much more efficient (removes two unnecessary joins) and lets you use the WP_Query orderby field to sort your posts rather than writing a custom query or filtering each of the SQL clauses of the query to make it do what you want.

share|improve this answer

I think that could be done with adding


to the query

share|improve this answer

First of all you shouldn't be using query_posts. Second, you should pass an array not a query string.

$query = new WP_Query( array( 
'category' => 'event',
'meta_key' => 'month', 
'meta_value' => 'June', 
'meta_compare' => '<' 
'orderby' => 'month')
//or whatever parameters you choose.
// The Loop
while ( $query->have_posts() ) : $query->the_post();
//your markup goes here

// Reset Post Data
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.