Two Nested Loops
-
Hi there,
I’d be most grateful to anyone that can shed any light on this – I’ve studied the documentation and I can’t see why this doesn’t work.
I’m trying to create a navigation list which will look something like this:
<ul> <li> <ul> <li></li> <li></li> <li></li> </ul> <ul> <li></li> <li></li> <li></li> </ul> </li> <li> <ul> <li></li> <li></li> <li></li> </ul> <ul> <li></li> <li></li> <li></li> </ul> </li> </ul>
It requires 3 loops: a country loop, and then within that a city loop and a town loop (to list cities and towns within a country).
I’m using the following code:
<ul> <?php # GET Countries $countryArgs = array( 'category_name' => 'country', 'posts_per_page' => -1, 'meta_key' => 'country-menu-order', 'orderby' => 'meta_value_num', 'order' => 'ASC' ); $sidebar_nav_loop = new WP_Query($countryArgs); if( $sidebar_nav_loop->have_posts() ): while( $sidebar_nav_loop->have_posts() ): $sidebar_nav_loop->the_post(); ?> <li class="<?php echo basename(get_permalink()); ?>"> <a href="<?php echo get_permalink(); ?>"> <?php the_title(); ?> </a> <?php # GET RELATED Cities $cityArgs = array( 'post_type' => 'post', 'posts_per_page' => -1, 'meta_key' => 'city-group', 'orderby' => 'meta_value_num', 'order' => 'ASC', 'meta_query' => array( array( 'key' => 'city-country', 'value' => '"' . get_the_ID() . '"', 'compare' => 'LIKE' ) ) ); $city_loop = new WP_Query($cityArgs); if( $city_loop->have_posts() ): ?> <ul> <li><a href="<?php the_permalink(); ?>" class="sub"><?php the_title(); ?></a></li> <?php while( $city_loop->have_posts() ): $city_loop->the_post(); ?> <li> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> </li> <?php endwhile; echo "</ul>"; endif; wp_reset_postdata(); ?> <?php # GET RELATED towns $townArgs = array( 'post_type' => 'post', 'posts_per_page' => -1, 'meta_key' => 'town-group', 'orderby' => 'meta_value_num', 'order' => 'ASC', 'meta_query' => array( array( 'key' => 'town-country', 'value' => '"' . get_the_ID() . '"', 'compare' => 'LIKE' ) ) ); $town_loop = new WP_Query($townArgs); if( $town_loop->have_posts() ): ?> <ul> <li><a href="<?php the_permalink(); ?>" class="sub"><?php the_title(); ?></a></li> <?php while( $town_loop->have_posts() ): $town_loop->the_post(); ?> <li> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> </li> <?php endwhile; echo "</ul>"; endif; wp_reset_postdata(); ?> </li> <?php endwhile; endif; wp_reset_postdata(); ?> </ul>
I can get the country and city to work, or the country and town, but I can’t get all three! To the best of my knowledge I’ve followed the documentation and reset the queries so they shouldn’t conflict.
Many thanks in advance for any help!
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
- The topic ‘Two Nested Loops’ is closed to new replies.