经过一段相当长的时间和几个查询/循环等,我确定这可以被清理,或者可能写得更好,但同时这对我来说是可行的!
<?php
// Loop through Categories and Display Posts within
// ACF Relationship Field based on CPT \'Locations\' - Post ID
$locations_field = $panel[\'locations\'];
// CPT \'Locations\'
$post_type = \'locations\';
// Get all the state taxonomy terms used
$state_terms = get_terms( array(
\'taxonomy\' => \'states\',
\'hide_empty\' => false,
\'parent\' => 0
) );
// Foreach term, loop through Locations posts selected in the relationship field filtered via the state terms. Not actually displaying anything with this query, but creating an array of post IDs.
foreach( $state_terms as $state_term ) : ?>
<?php
$args = array(
\'post_type\' => $post_type,
\'posts_per_page\' => -1, //show all posts
\'post__in\' => $locations_field,
\'tax_query\' => array(
array(
\'taxonomy\' => \'states\',
\'field\' => \'slug\',
\'terms\' => $state_term->slug,
)
)
);
$new_posts = new WP_Query($args);
$ids = array();
if( $new_posts->have_posts() ): while( $new_posts->have_posts() ) : $new_posts->the_post(); ?>
<?php array_push( $ids, get_the_ID() ); ?>
<?php endwhile; endif; ?>
<?php // Begin to display groups starting with the State term
if (!empty($ids)) : // CHECK TO MAKE SURE THERE ARE POSTS! ?>
<h2><?php echo $state_term->name; // State name ?></h2>
<?php
// Get all the city taxonomy terms used
$city_terms = get_terms( array(
\'taxonomy\' => \'cities\',
\'hide_empty\' => false,
\'parent\' => 0
) );
foreach( $city_terms as $city ) : ?>
<?php
$args2 = array(
\'post_type\' => $post_type,
\'posts_per_page\' => -1, //show all posts
\'tax_query\' => array(
array(
\'taxonomy\' => \'cities\',
\'field\' => \'slug\',
\'terms\' => $city->slug,
)
),
\'post__in\' => $ids // The array of IDs previously gathered
);
$posts2 = new WP_Query($args2);
if( $posts2->have_posts() ): ?>
<div class="location-city">
<h2><?php echo $city->name; // City name ?></h2>
<?php while( $posts2->have_posts() ) : $posts2->the_post(); ?>
<h3><?php echo get_the_title(); ?></h3>
<?php endwhile; ?>
</div>
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>
<?php endforeach; ?>