Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- get_posts(array(
- 'post_type' => 'gallery',
- 'tax_query' => array(
- array(
- 'taxonomy' => 'gallery_cat',
- 'field' => 'term_id',
- 'terms' => 45)
- ))
- );
- ?>
- 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.
- Here’s another example which will select all posts with the terms ‘Sunsets’ and ‘Nature’, based on the same custom taxonomy. As you can see, to select multiple terms from the custom taxonomy, we need to put them as a comma seperated string within an array.
- <?php
- get_posts(array(
- 'showposts' => -1,
- 'post_type' => 'gallery',
- 'tax_query' => array(
- array(
- 'taxonomy' => 'gallery_cat',
- 'field' => 'name',
- 'terms' => array('Sunsets', 'Nature'))
- ),
- 'orderby' => 'title',
- 'order' => 'ASC')
- );
- ?>
- Finally, we can put all this in a simple loop to display our content, title and ID of all posts belonging to our chosen terms.
- <?php
- $myposts = get_posts(array(
- 'showposts' => -1,
- 'post_type' => 'gallery',
- 'tax_query' => array(
- array(
- 'taxonomy' => 'gallery_cat',
- 'field' => 'slug',
- 'terms' => array('sunsets', 'nature'))
- ))
- );
- foreach ($myposts as $mypost) {
- echo $mypost->post_title . '<br/>';
- echo $mypost->post_content . '<br/>';
- echo $mypost->ID . '<br/><br/>';
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement