Support

Account

Home Forums Add-ons Repeater Field Return a certain number of rows based on date

Solved

Return a certain number of rows based on date

  • Hi
    I have a repeater where each row has an expiration date.
    I would like to show only 3 rows where the items have not expired.

    My code so far:`
    <?php date_default_timezone_set( ‘America/Los_Angeles’ );
    $today = date( ‘Ymd’ );
    if ( have_rows( ‘events’, 2006 ) ):
    while ( have_rows( ‘events’,
    2006 ) ) : the_row();
    $expire = get_sub_field( ‘expire_on’,
    2006 );
    if ( $expire > $today ):
    ?>
    <li class=”eventrow event<?php echo get_row_index(); ?>”>
    <h3><a target=”_blank”
    href=”<?php the_sub_field( ‘events_link’,
    2006 ); ?>”><?php the_sub_field( ‘events_title’,
    2006 ); ?></a></h3>
    <p><?php the_sub_field( ‘events_date’,
    2006 ); ?> <br>
    <em> <?php the_sub_field( ‘events_location’,
    2006 ); ?> </em></p>
    </li>
    <?php endif; endwhile; endif; ?>`

    I know that my method of hiding expired rows is not ideal.. show me how to do it better?

    Thanks!

  • Hi @mrspabs

    Below is some code cleaned up a bit. I am assuming that 2006 is your Post ID? You don’t need to pass that to sub fields of your repeater, but it doesn’t hurt.

    I just added an extra bit to the ‘while’ statement making sure to only loop 3 times. I created the iteration variable just above the while statement with a value of 0. I then increment that value at the end of the while. Hope this helps! Please mark this thread as resolved if so, otherwise please reply with more questions.

    <?php
    date_default_timezone_set( 'America/Los_Angeles' );
    $today = date( 'Ymd' );
    if ( have_rows( 'events', 37 ) ) {
    ?>
    <ul>
    <?php
      $i = 0;
      while ( have_rows( 'events', 37 ) && $i<4 ) {
        the_row();
        $expire = get_sub_field( 'expire_on' );
        if ( $expire > $today ) {
    ?>
    <li class="eventrow event<?php echo get_row_index(); ?>">
      <h3>
        <a target="_blank" href="<?php the_sub_field( 'events_link' ); ?>">
          <?php the_sub_field( 'events_title' ); ?>
        </a>
      </h3>
      <p>
        <?php the_sub_field( 'events_date' ); ?><br />
        <em><?php the_sub_field( 'events_location' ); ?></em>
      </p>
    </li>
    <?php
        }
        $i++;
      }
    ?>
    </ul>
    <?php
    }
    ?>

    p.s. Thanks for teaching me about the get_row_index() function!

  • Thank you! That worked perfectly!

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Return a certain number of rows based on date’ is closed to new replies.