Query Custom Post Type taxonomy type based on page

To make that more efficient, instead of arguing the current page slug, you just place the current slug as the tax_query’s terms value. Something like:

global $post;
$args = array(
  'posts_per_page' => -1,
  'post_type' => 'books',
  'post_status' => 'publish',
  'tax_query' => array(
      array(
          'taxonomy' => 'book_category',
          'field'    => 'slug',
          'terms'    => $post->post_name, // which'd be `horror` or `comedy`, etc
      ),
  ),
);

Note that there’s high probability of human error doing things this way: for example having a page of nonfiction but a book_category term of non-fiction could break the logic and cause problems.

I don’t know the context of what you’re working on, but if the goal is just “each of these categories have their own respective page” you do not need to build this custom-query-with-manual-page-relation for each term. WordPress taxonomies and terms will have their own URLs if you’ve registered the taxonomy as public and publicly_queryable. (Guessing here, but) You can probably visit your-site.com/book_category/horror/ and see the list of horror books. You can then customize the template files for all terms or individually using the WordPress template hierarchy as reference.

Leave a Comment