Show Posts Based On Custom Taxonomy ID

Quick Summary
- Add a tax_query to your WP_Query arguments with the taxonomy name and term ID to get only posts assigned to that term.
- The example gets team posts in term 12 of the company-category taxonomy; pass an array of IDs to include several terms.
- Posts in child terms of a hierarchical taxonomy are included unless you set include_children to false in the tax query.
To show only the posts that belong to one term of a custom taxonomy, add a tax_query to your WP_Query arguments. This example gets posts of the custom post type team that are assigned to the term with ID 12 in the company-category taxonomy.
$team_args = array(
'post_type' => 'team',
'posts_per_page' => 99,
'tax_query' => array(
array(
'taxonomy' => 'company-category',
'field' => 'id',
'terms' => 12
)
),
);How it works
post_typeis the custom post type to query, hereteam.posts_per_pagecaps the results at 99. Use-1to get every matching post.taxonomyis the taxonomy’s registered name, andtermsis the term ID. Pass an array of IDs to include several terms. To combine conditions on two taxonomies, add a second array and arelationkey, as in matching both a category and a tag.'field' => 'id'matchestermsagainst term IDs. The documented value isterm_id, which is also the default;slugandnamelet you match terms by those instead.
To find a term’s ID, open the term’s edit screen in the admin and look for tag_ID= in the URL.
The array only defines the query. Pass it to new WP_Query( $team_args ) in your template, loop through the results with have_posts() and the_post(), and call wp_reset_postdata() after the loop. For hierarchical taxonomies, posts in child terms of term 12 are included too, unless you add 'include_children' => false to the tax query.
Related articles
- WooCommerce products by category ID: the same tax_query with the product_cat taxonomy
- pagination for a custom post type query: when the results need more than one page
See also: MySQL: Delete WordPress Custom Posts Within a Date Range.

