Search code examples
phpwordpresssortingadvanced-custom-fields

Sort custom post types by acf date repeater field


I have a custom post type called project. Since each project can have multiple happening dates, I created a repeater field date-and-time named dates with a sub-field named date.

I would like to display all the posts in a page like following (sorted by acf sub field date):

project A: 10th march
project B: 17th march
project A: 21st march
project C: 30th march
project A: 5th april
project B: 12th april
and so on...

How can I achieve this?


Solution

  • Here is how I did it, if it can help somebody facing the same issue. I created an array containing post id and date repeater field and loop through it.

    $events = new WP_Query(array('post_type' => 'project'));
    if($events->have_posts()) :
      $listPostEvents = array(); // creating an empty array 
      while ( $events->have_posts() ) : $events->the_post();
    
        if (have_rows('repeater_dates')): // name of the repeater field
          while (have_rows('repeater_dates')) : the_row();
            $date = strtotime( get_sub_field('start_date_repeat') ); // keep the date as Unix timestamp format - easier to sort
              $listPostEvents[] = array(
                'date'      => $date,
                'ID'        => $post->ID
              );
          endwhile;
        endif;
    
      endwhile;
    
      $dates = array_column($listPostEvents, 'date'); // list all dates
      array_multisort($dates, SORT_ASC, $listPostEvents); // sort these dates chronologically
        foreach ($listPostEvents as $listPostEvent) : // loop through the array sorted by dates
            $postID = $listPostEvent['ID'];
    
            echo '<article class="event post-' . $postID . '">';
              echo '<a href="' . esc_url( get_permalink($postID) ) . '">';
                the_post_thumbnail('large');
              echo '</a>';
              echo '<time>' . date_i18n( "d.m.Y", $listPostEvent['date'] ) . '</time>'; // echo the dates in day.month.Year translatable format
              echo '<a href="' . get_permalink($postID) . '">' . get_the_title($postID) . '</a>';
            echo '</article>';
    
        endforeach;
    endif;