Order Custom WordPress Posts by Custom Field using Advanced Custom Fields

I am trying to order a set of custom post by time using Advanced Custom Fields (ACF). Using this help page and the WP_Query page from the codex, I’ve gotten to the code below, but it only sorts by the post title, I want it to sort by the custom field start_time I’ve created.

Here are some of the possible key/values a user can pick:

Read More

a : 6:00am

b : 6:15am

c : 6:30am

d : 6:45am

And here is a simplified version of the template code:

<?php $args = array( 
'post_type' => 'events', 
'posts_per_page' => -1,
'orderby'           => 'meta_value_char',
'meta_key'          => 'start_time',
'order'             => 'ASC'
);

$loop = new WP_Query( $args ); ?>
    <ul> 
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

    <li>
        <?php the_title(); ?>: <?php the_field( "start_time" ); ?>
    </li>

<?php endwhile; ?>
</ul>

Which outputs this:

  • A Event: 7:45am
  • B Event: 4:15pm
  • C Event: 7:45am
  • D Event: 2:30pm
  • E Event: 10:15am

So it’s ordering the posts by the event title, not the time field. how can I make it order by the time field I created? Thanks!

Related posts

1 comment

  1. I have three options for you. I have not tested them.

    Orderby can accept more than one argument.

    'orderby'  => 'meta_value meta_value_char'
    

    Is the time is stored as a num? Then try these. One at a time, not together.

    'orderby'  => 'meta_value meta_value_num'
    
    'orderby'  => 'meta_value_num'
    

    I hope that helps.

    Best.

Comments are closed.