Sort by ascending date PHP array with Advanced Custom Fields

150 views Asked by At

I'm trying to order my custom posts by the most recent date and I can't get it to work. Am I missing something?

<?php
$args = array(
'post_type' => 'event',
'post_status' => 'publish',
'posts_per_page' => '10',
'meta-key' => 'event_date',
'orderby' => 'meta_value_num',
'order' => 'ASC'
);

$event_loop = new WP_Query( $args );
if ( $event_loop->have_posts() ) :
while ( $event_loop->have_posts() ) : $event_loop->the_post();
  // Set variables
  $title = get_the_title();
  // Output
  ?>
<a class="class" href="<?php echo get_permalink(); ?>"><h2><?php echo $title; ?></h2></a>
<img style="float: right; max-width: 28%;"src="<?php the_field('event_image'); ?>"/><h3>Event Date : <?php the_field('event_date'); ?></h3>
1

There are 1 answers

2
Bizmate On

'order' => 'ASC' means from the oldest to the newest. Try with

 'order' => 'DESC'

Also notice your are ordering on a non date field meta_value_num

Try ordering by a date field that you want to use.

For instance use

'orderby' => 'date'

if your table contains a date for each event. The orderby needs the name of the column with a date type that you want to use to sort the posts/events.

See an example of the wp_posts table here https://codex.wordpress.org/Database_Description#Table:_wp_posts

An example of a query that works with the wp_posts is shown here

WP_Query('orderby=date&order=DESC')