How to order wordpress posts by a custom field dat

2020-07-18 04:50发布

问题:

I am making an event sidebar section that will only display the next 3 events. I have got the custom post type and custom fields all working but I can seem to figure out how to order the posts by the start date of the events, which is a custom field value. Is there a php function that can compare dates and organize them into a certain order. I think it would also have to hold the post-id with the newly arranged dates so that when I read through the values, i can display the appropriate post with that date.

Does anyone have a certain direction to steer me in?

I think this is what I need to do:

  1. Read through the posts and grab the dates
  2. Sort the dates with the post-id associated with those dates
  3. Read through the sorted dates and re-display the first 3 posts by post-id

I get lost on how to code that though... This is what I have so far. This code just displays them by their publish dates in wordpress.

<?php query_posts('post_type=events');
            if (have_posts()) : while (have_posts()) : the_post(); ?>
                <?php $dateStart = get_post_meta($post->ID, 'date-start', true);?>
                <div class="date"><?php echo $dateStart; ?></div>

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

回答1:

I believe I was able to answer my own question. Wordpress has a built in feature to compare custom field values between posts. To compare dates, which was my custom field value, they have to be in 'yyyymmdd' format to easily be able to compare them.

I was really surprised that I didnt have to make multiple loops and store post-ids or anything. Anyways, I hope this helps someone else. :]

 <?php 
        $args = array(
           'post_type' => 'events',
           'posts_per_page' => 3, //limited myself to 3 posts
           'meta_key' => 'date-start', //name of custom field
           'orderby' => 'meta_value_num', 
           'order' => 'ASC'
        );
        query_posts($args);
        if (have_posts()) : while (have_posts()) : the_post(); ?>
            //Insert code here...
            //Test to see if it is sorting the posts (below)
            <?php $dateStart = get_post_meta($post->ID, 'date-start', true); echo $dateStart;?>

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