Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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(); ?>
    <li>
        <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>
        <div class="details">
            <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> &rarr;</h3>
        </div>
    </li>
<?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
add comment

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

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

3 Answers

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
add comment

I think that could be done with adding

meta_key=yourcustomfield&orderby=meta_value

to the query

share|improve this answer
add comment

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
endwhile;

// Reset Post Data
wp_reset_postdata();
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.