Support

Account

Home Forums ACF PRO Sorting repeater fields by date Reply To: Sorting repeater fields by date

  • The above code will just sort by the date field. More complex sorting can be accomplished. For example if you want to group all of the posts from a month without considering what year the date is in the you could use date functions on the field above the if statement and then base your if statements on the calculations of whatever manipulation you do to the values.

    Grouping by month is en entirely different issue and you need to do this grouping using PHP

    
    // set starting month and count
    // we need a counter to know if we're on the first row
    $previous_month = '';
    $count = 0;
    foreach ($repeater as $row) {
      // make sure that your date field is returning a valid date format
      // or this will not work
      $this_month = date('m', strtotime($row['YOUR_DATE_FILED']));
      if ($this_month != $last_month) {
        // month has changed
        if ($count > 0) {
          // close the previously opened container
          // the container is opened below
          ?>
            </div><!-- .month -->
          <?php 
        } // end in count > 0 (i.e. not first row)
        // open a new container and display the month
        ?>
          <div class="month">
            <div class="the_month"><?php echo $month; ?></div>
        <?php 
        
        // update previous month value for next loop
        $previous_month = $this_month;
    
      } // end if new month
    
      // output additional sub fields here
    
      // increment count
      count++;
      
    } // end foreach row