Home > front end >  WordPress ACF Reapeater Date Field Return Only First Entry For Each Month
WordPress ACF Reapeater Date Field Return Only First Entry For Each Month

Time:10-29

I have an ACF repeater field with a dates sub field to add departure dates on a tour operators website. On the front end I have a tabs component used for displaying/filtering the departure dates by month.

In order to build the component I check for rows to to create the filtering menu which returns only the formated month.

  <?php if( have_rows('departure_dates') ): ?>

    <div >

      <?php while( have_rows('departure_dates') ): the_row(); ?>

      <?php 
        $dateMonth = get_sub_field('date', false, false);
        $dateNew = new DateTime($dateMonth);
      ?>    

        <button ><span><?php echo $dateNew->format('M'); ?></span></button>

      <?php endwhile; ?>

    </div>

  <?php endif; ?>

Then I check for rows again to build the dates list without formatting the returned date:

  <?php if( have_rows('departure_dates') ): ?>

    <div >

      <?php while( have_rows('departure_dates') ): the_row(); ?>

      <div >

        <?php $date = get_sub_field('date'); ?>

        <?php if( $date ): ?>

          <?php echo $date; ?>

        <?php endif; ?>

      </div>

      <?php endwhile; ?>

    </div>

  <?php endif; ?>

The problem I have is that months with multiple departure dates get displayed on the filtering menu. I'd like to only show the first row for each month that has an entry

So this:

<button>JAN</button>
<button>JAN</button>
<button>JAN</button>
<button>FEB</button>
<button>FEB</button>
<button>MAR</button>

Becomes this:

<button>JAN</button>
<button>FEB</button>
<button>MAR</button>

How do I return only the first entry for each month? Any help would be great

Many thanks in advance

CodePudding user response:

You can keep track of what you have looped through and conditionally display, something like this:

<?php if (have_rows('departure_dates')) : ?>

    <div >

        <?php

        $found_months = [];

        ?>

        <?php while (have_rows('departure_dates')) : the_row(); ?>

            <?php
            $dateMonth = get_sub_field('date', false, false);
            $dateNew = new DateTime($dateMonth);
            $current_month = $dateNew->format('M');
            ?>

            <?php if (!in_array($current_month, $found_months)) : ?>
                <button ><span><?php echo $current_month; ?></span></button>
            <?php endif; ?>


            <?php 
            
            $found_months[] = $current_month;

            ?>

        <?php endwhile; ?>

    </div>

<?php endif; ?>
  • Related