Ultimate Web Tips
your Wordpress, jQuery, PHP, MySQL, Linux and CSS guide to a successful website
Read more:

March 27th, 2012

Get all posts on custom taxonomy slug with get_posts

Wordpress, by Joakim Ling.

Custom post typesCustom post type is a great way to customize your WordPress and adding new taxonomies makes it even more powerful. All functionality comes with WordPress core but it can be difficult to specific posts on a custom taxonomy. The key in this is the new tax_query argument.

tax_query

It’s a new argument that replaces “tax” in the old query arguments. Which is now deprecated. You send as an array and you can include different taxonomies or exclude them.

  • taxonomy (string) – Taxonomy
  • field (string) – Select taxonomy term by (‘id’ or ‘slug’)
  • terms (int/string/array) – Taxonomy term(s).
  • include_children (boolean) – Whether or not to include children for hierarchical taxonomies. Defaults to true.
  • operator (string) – Operator to test. Possible values are ‘IN’, ‘NOT IN’, ‘AND’.

Get all post on a taxonomy slug

I’d assume we have a custom post type, let’s call it “book”, and a custom taxonomy called “book-type”.

To get all books that has the “book-type” “fantasy” see example below

$args = array(
  'post_type' => 'book',
  'showposts' => -1,
  'tax_query' => array(
    array(
      'taxonomy' => 'book-type',
      'field' => 'slug',
      'terms' => 'fantasy'
    )
  ),
  'orderby' => 'title',
  'order' => 'ASC'
);
$books = get_posts($args);

If we want all books that are fantasy and horror

      'terms' => array('fantasy', 'horror')

Read more on WordPress Codex about WP_Query, click here

Themedy Thesis & Genesis Skin Club

Themedy is a premium skin marketplace offering quality child themes for the some of the most popular Wordpress frameworks like Thesis & Genesis. Read more

Back Top

Club World Casinos