You are looping through all states and running a query on each iteration, but the query you are doing is nothing to do with the loop. You are checking for $_GET['state']
, which would be the state passed over the query string.
<?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'
)
)
) );
?>
So, you could just swap that out for $state
– but then you still have a very inefficient method, as you’re making 50 queries!
Instead, I would do a single query, then loop through the results, using get_the_terms( $post->ID, 'states' )
to get the state of every post. Instead of outputting directly, I would build an array. The following is very rough and untested:
// 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
Only when that loop was complete and the array was built, would I then iterate through my new array to output the results. Something like:
<?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>
<?
}
?>