Get Post by Custom Taxonomy

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:

  1. ‘taxonomy’- the slug that is used to identify the taxonomy.
  2. ‘field’ – can be either ‘term_id’ (the numeric ID of the term), ‘slug’ or ‘name’ (the term name such as ‘Sunsets’)
  3. ‘terms’ – will need to be the ID value, slug or name depending what ‘field’ is set to.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s