Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
    
I did not test it, but tax_query is supposed to take an array of arrays‌​, so maybe try: $wp_query->set('tax_query', array( array('include_children' => false))); –  goto10 Jun 14 '12 at 20:24
    
Okay, just tried that, but no luck. With the extra array it gives me a 'Page not found' error. –  Sam Jun 14 '12 at 21:27
add comment

1 Answer 1

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:

function exclude_children($wp_query) {
    if ( isset ( $wp_query->query_vars['custom_taxomony'] ) ) {
        $wp_query->set('tax_query', array( array (
            'taxonomy' => 'custom_taxonomy',
            'field' => 'slug',
            'terms' => $wp_query->query_vars['custom_taxonomy'],
            'include_children' => false
        ) )
    }
}  
add_filter('pre_get_posts', 'exclude_children'); 

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, and terms are all required values, though that's not clear from the Codex.

share|improve this answer
    
I never quite figured this out, so you definitely got further than I did. Can you get the taxonomy dynamically via get_query_var('taxonomy')? –  helgatheviking Mar 17 '13 at 19:32
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.