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.

PHP
$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_type is the custom post type to query, here team.
  • posts_per_page caps the results at 99. Use -1 to get every matching post.
  • taxonomy is the taxonomy’s registered name, and terms is the term ID. Pass an array of IDs to include several terms. To combine conditions on two taxonomies, add a second array and a relation key, as in matching both a category and a tag.
  • 'field' => 'id' matches terms against term IDs. The documented value is term_id, which is also the default; slug and name let 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.

See also: MySQL: Delete WordPress Custom Posts Within a Date Range.

Share on X (opens in a new tab) Share on LinkedIn (opens in a new tab) Share on Facebook (opens in a new tab)

ChatGPT (opens in a new tab) Claude (opens in a new tab) Gemini (opens in a new tab) Perplexity (opens in a new tab) Grok (opens in a new tab)

More Insights

See More