I have created two custom taxonomies (1. Business location and 2. Business Category) for a custom post type (Business Listing). Now I have listed all the location under Location taxonomy archive where I have listed all the locations and when the user clicks on Location A it takes user to post archive page of Location A where all the posts are listed from that specific taxonomy.
Here is where I want to list each Business Category on top and below it all the post of specific Business Category
Example: in domain.com/locations/location1/
Category 1
Post 1
Post 2
Post 3
Category 2
Post 1
Post 2
Post 3
How do I accomplish this?
I did try few options but below code gets the post from all the locations but I want to list the categories and post from the current location.
<?php
$taxonomy = 'business-category';
$args = array(
'orderby' => 'id',
'order' => 'ASC',
);
$taxonomy_terms = get_terms($taxonomy, $args);
if($taxonomy_terms) {
foreach($taxonomy_terms as $taxonomy_term) {
$args = array(
"$taxonomy" => $taxonomy_term->slug,
'post_status' => 'publish',
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) : ?>
<h2><?php echo $taxonomy_term->name; ?></h2>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<h3><?php the_title(); ?></h3>
<?php endwhile; ?>
<?php wp_reset_postdata(); endif;
}
}
?>
Answer Modified from Ben HartLenn
<?php
$business_location = get_queried_object();
$business_categories = get_terms( [
'taxonomy' => 'business-category',
'hide_empty' => true,
] );
$duplicates = [];
foreach ( $business_categories as $business_category ) :
?>
<?php $args = [
'post_type' => 'business-listing',
'tax_query' => [
'relation' => 'AND',
[
'taxonomy' => 'business-location',
'field' => 'slug',
'terms' => $business_location->slug,
],
[
'taxonomy' => 'business-category',
'field' => 'slug',
'terms' => $business_category->slug,
],
],
'post__not_in' => $duplicates,
];
$query = new WP_Query( $args );
?>
<div class="business-listing-block">
<?php if ( $query->have_posts() ) : ?>
<h2 class='business-category-title'><?php echo $business_category->name; ?></h2>
<ul class='business-listings'>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<?php if ( ! in_array( $post->ID, $duplicates ) ) {
$duplicates[] = $post->ID;
} ?>
<li class='business-listing'><?php echo the_title(); ?> </li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
</div>
<?php endforeach; ?>