Hey. I’m having difficulty getting my head around nested loops. The data structure is like this:
tour (custom post type)
– tour_dates (repeater field)
– tour_info (group sub field)
– start_date (date picker sub field)
I would like to print out all tours by date. There are around 70 tours, and inside each one will be 1 or 2 dates. The tours will have a destination category assigned. Ideally I need to print out each date and tour name, in order, and so far my loop is separating the dates by tour destination rather than mixing them in. Here’s the code so far:
<?php $args = array( 'post_type' => 'tour', 'posts_per_page' => -1, 'orderby' => 'start_date', 'order' => 'ASC' ); $new_query = new WP_Query( $args ); if ( $new_query->have_posts() ) : while ( $new_query->have_posts() ) : $new_query->the_post(); if ( have_rows('tour_dates') ): while ( have_rows('tour_dates') ) : the_row(); if ( have_rows('tour_info') ): while ( have_rows('tour_info') ) : the_row(); ?> <li> <span><?php echo get_sub_field('start_date'); ?> to <?php echo get_sub_field('end_date'); ?></span> </li> <?php endwhile; endif; endwhile; endif; endwhile; endif; ?>
I’ve attached a screenshot of the result. A couple of problems – the last two dates are from a separate destination category, and they are not being mixed in with the dates above (which are all the same destination category). And the very first two dates are from the same tour (and destination category), but they are a year apart! So the second date set should be at the end. I hope this makes sense…!
@edank thanks for your response. It is a sub_field I believe – I think my indentation didn’t come through properly. Screenshot attached. Tours are assigned a destination category, and each destination may have numerous tours, and then for each tour there are numerous dates. Hence why tour_dates is a repeater, and tour_info is the group of variables for that specific tour.
hey, does the current order match how it’s inputed in the admin?
Have you tried sorting them first before looping through?
This url might help:
The topic ‘Nested Loop’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!