I have created a custom hierarchical taxomony and when viewing a taxonomy archive page would like to only display the posts that have been assigned to that term. This works fine on the child term pages, but the parent term pages display posts assigned to them AND any child terms.
I found a solution that solves this for categories by inserting the following link after the beginning of the loop:
<? if ((is_category()) && in_category($wp_query->get_queried_object_id())) { ?>
But I haven’t been able to find a similar solution that works for custom taxonomies.
I also tried:
function exclude_children($wp_query) {
if ( isset ( $wp_query->query_vars['custom_taxomony'] ) ) {
$wp_query->set('tax_query', array('include_children' => false));
}
}
add_filter('pre_get_posts', 'exclude_children');
But that does not seem to have any effect. So the question is, how do I do this?
Okay, I’ve found an answer. Part of the issue was the missing array @goto10 mentioned, and the other part was that tax_query has required arguments. Here’s what I’m using so far:
I’d prefer to be using a variable for
taxonomy => custom_taxonomy
rather than hard coding the value in as that seems like a more reusable solution, but I don’t know how to pull the values from the WP_Tax_Query object.The important takeaway from this is that
taxonomy
,field
, andterms
are all required values, though that’s not clear from the Codex.An empty $taxonomy_slugs array will exclude children for all taxonomy archives.
I used query_posts() to achieve this:
Then your loop …
As @Sam said,
taxonomy
,field
, andterms
are all required fortax_query()
(this tripped me up).