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


3 Answers 3


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.


I think that could be done with adding


to the query


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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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