I finally got it to work properly. I am posting the solution so maybe other people need something similar can use it.
It seems what I needed to do is use get_posts
with the same arguments as WP_Query
and check if there are posts by modifying the “if” statement already existed inside “foreach”.
All code
<?php function get_stations_query($current_genre) {
$loc_term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
$query = new WP_Query( array(
'post_type' => 'stations',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => 'genres',
'field' => 'name',
'terms' => $current_genre,
'operator' => 'AND'
),
array(
'taxonomy' => 'locations',
'field' => 'name',
'terms' => $loc_term->name
)
)
) );
if ($query->have_posts()) : while ( $query->have_posts() ) : $query->the_post();
get_template_part('loop-stations');
endwhile; wp_reset_postdata(); else : ?>
<p>Sorry, no radio stations found.</p>
<?php endif;
} ?>
<?php function generate_genres() {
$genresrays = array (
'pop_genre' => 'Pop',
'rock_genre' => 'Rock',
'jazz_genre' => 'Jazz',
'soul_genre' => 'Soul',
'ethnic_genre' => 'Ethnic',
'trance_genre' => 'Trance',
'country_genre' => 'Country',
'chill_out_genre' => 'Chill Out',
);
foreach ($genresrays as $genresray=>$genre_value) {
$ex_term = term_exists($genre_value, 'genres');
$loc_term_s = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
$grab = get_posts(array(
'post_type' => 'stations',
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'genres',
'field' => 'name',
'terms' => $genre_value,
'operator' => 'AND'
),
array(
'taxonomy' => 'locations',
'field' => 'name',
'terms' => $loc_term_s->name
)
))
);
if (!empty($grab) && $ex_term !== 0 && $ex_term !== null) { ?>
<div class="clearfix"></div>
<hr style="margin: 30px 0;">
<div id="<?php echo strtolower(str_replace(' ','-',$genre_value)); ?>" class="clearfix">
<h3 style="margin-top: 20px !important;"><?php echo $genre_value; ?></h3><br>
<?php get_stations_query(strtolower($genre_value)); ?>
</div>
<?php }
}
} ?>