Taxonomies are basically a way of grouping data in WordPress. The most common default taxonomies used in WordPress are when grouping posts as either ‘categories’ or ‘tags’ and these are named and recorded in the WordPress database as ‘category’ and ‘post_tag’ respectively. Specific categories or tags are called terms.
Many plugins and theme functionality will use their own custom taxonomies to group data together in a meaningful way. A photo gallery for example might have a taxonomy name ‘gallery_cat’ with terms such as ‘Sunsets’, ‘Portraits’, ‘Nature’ etc. Each term has an associated name, slug and term ID.
To query WordPress and return posts based on these custom taxonomy names and terms, we can use ‘tax_query’ within get_posts() as indicated below:
<?php $args = array( 'post_type' => $post_type, 'tax_query' => array( array( 'taxonomy' => $taxonomy, 'field' => 'term_id', 'terms' => 45) )); query_posts($args); if ( have_posts() ) : while (have_posts()) : the_post(); /* your code goes here */ endwhile; endif; wp_reset_query(); ?>
The ‘tax_query’ array takes 3 required arguments:
- ‘taxonomy’- the slug that is used to identify the taxonomy.
- ‘field’ – can be either ‘term_id’ (the numeric ID of the term), ‘slug’ or ‘name’ (the term name such as ‘Sunsets’)
- ‘terms’ – will need to be the ID value, slug or name depending what ‘field’ is set to.