My WordPress theme includes a custom taxonomy known as "Collections". The custom taxonomy is hierarchical, so you will find subcollections.

I've got a Collection known as "Books" along with a sub-collection known as "Books". You will find some posts which are just in "Books", plus some posts which are in "Books". I would like the page for that "Books" collection to simply show posts within the primary "Books" collection, not those within the "Books" subcollection. But automatically, WordPress includes posts in "subcollections" within the query for any taxonomy.

How do you exclude posts in child terms from the taxonomy query? This really is easy with groups, however it appears there's no built-in method of doing this with custom taxonomies.


Update: Jan's solution labored perfectly. This is actually the code I made use of, placed over the Loop in index.php:

// if is taxonomy query for 'collections' taxonomy, modify query so only posts in that collection (not posts in subcollections) are shown.
if (is_tax()) {
 if (get_query_var('collection')) {
  $taxonomy_term_id = $wp_query->queried_object_id;
  $taxonomy = 'collection';
  $unwanted_children = get_term_children($taxonomy_term_id, $taxonomy);
  $unwanted_post_ids = get_objects_in_term($unwanted_children, $taxonomy);

  // merge with original query to preserve pagination, etc.
  query_posts( array_merge( array('post__not_in' => $unwanted_post_ids), $wp_query->query) );
 }
}

It appears the Wordpress_Query class always includes all items of hierarchical taxonomies. If you wish to counter this, you should use exactly the same trick they will use: get all subitems of the taxonomy item, then get all of the publish id's in individuals subitems, after which insert them in the post__not_in parameter:

$unwanted_children = get_term_children($taxonomy_term_id, $taxonomy);
$unwanted_post_ids = get_objects_in_term($unwanted_children, $taxonomy);

This can lead to a question which has AND posts.ID IN (1, 2, 3) AND posts.ID NOT IN (2, 3), that will return only this publish with ID 1. Very unelegant, however it works.

Obviously, should you follow this path, you might just pass the publish id's you would like, and tell the query nothing concerning the taxonomy.

How can you do that for groups? The query code seems to include children there too.