您正在遍历所有状态并在每次迭代中运行查询,但您所做的查询与循环无关。您正在检查$_GET[\'state\']
, 这将是通过查询字符串传递的状态。
<?php
foreach ( $states as $state ) {
$state_query = new WP_Query( array(
\'post_type\' => \'dealers\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'states\',
\'field\' => \'name\',
\'terms\' => $_GET[\'state\'],
\'operator\' => \'IN\'
)
)
) );
?>
所以,你可以把它换成
$state
- 但是你仍然有一个非常低效的方法,因为你要进行50次查询!
相反,我将执行单个查询,然后使用get_the_terms( $post->ID, \'states\' )
获取每个帖子的状态。我将构建一个数组,而不是直接输出。以下内容非常粗略且未经测试:
// start your loop here
$states = get_the_terms( $post->ID, \'states\' );
$dealers[$states[0]->name][] = array(
\'dealer_name\' => $post->post_title,
\'street_address\' => get_field (\'street_address\', $post->ID),
\'dealer_city\' => get_field (\'dealer_city\', $post->ID),
// and so forth for all fields
)
// end your loop here
只有当循环完成并构建了数组时,我才会遍历新数组以输出结果。类似于:
<?php
$old_state = \'\';
foreach ( $dealers as $state => $dealer ) {
if ( $state != $old_state ) {
?>
<h3 class="state"><?php echo $state; ?></h3>
<?php
$old_state = $state;
}
?>
<div class="dealer">
<h4 class="dealer_name"><?php the_title(); ?></h4>
<p><?php echo $dealer[\'street_address\']; ?></p>
<p><?php echo $dealer[\'dealer_city\']; ?></p>
<!-- all the other fields... -->
</div>
<?
}
?>