Query Custom Post Type taxonomy type based on page

I have a Custom Post Type called books. This Custom Post Type has a taxonomy called book_category. As of now, and in the foreseeable future, there are 5 categories each book can be filtered under.

Now, each of these categories have their own respective page that will query the books based on respective category (among other ancillary information pertaining to each category).

In my code below, I made an attempt to query posts based on is_page(). While this DOES work… something is telling me there’s a more efficient / proper way of handling this.

<?php
if (is_page(‘horror’)) {
$theTermBasedOnPage = ‘horror’;
} elseif (is_page(‘comedy’)) {
$theTermBasedOnPage = ‘comedy’;
} elseif (is_page(‘romantic’)) {
$theTermBasedOnPage = ‘romantic’;
} elseif (is_page(‘nonfiction’)) {
$theTermBasedOnPage = ‘nonfiction’;
} elseif (is_page(‘drama’)) {
$theTermBasedOnPage = ‘drama’;
}

$args = array(
‘posts_per_page’ => -1,
‘post_type’ => ‘books’,
‘post_status’ => ‘publish’,
‘tax_query’ => array(
array(
‘taxonomy’ => ‘book_category’,

‘terms’ => $theTermBasedOnPage,
),
),
);
?>

What is the best way to query posts (Custom Post Type > Taxonomy) based on page?

Read more here:: Query Custom Post Type taxonomy type based on page

Leave a Reply

Your email address will not be published. Required fields are marked *