17

I have a custom post type called 'episode'. Attached to 'episode' I have a custom taxonomy called 'video_type' that contains two terms: "bonus-footage" and "episode"; "episode" contains two child terms "season-1" and "season-2" (other seasons will be added in the future). I want to grab only the most recent post of the 'episode' type but not include any posts from the 'bonus-footage' term. Below is the code I'm using for this:

<?php
$some_args = array(
    'tax_query' => array(
        'taxonomy' => 'video_type',
        'terms' => 'bonus-footage',
        'field' => 'slug',
        'include_children' => true,
        'operator' => 'NOT IN'
     ),
    'posts_per_page' => 1,
    'post_type' => 'episode',
);

$s = new WP_Query( $some_args );

if ( $s->have_posts() ) : $s->the_post();
    // Do something with this post.
endif;
?>

The query works as expected if a post in one of the 'season' terms is the newest, but if a post in "bonus-footage" is the newest, then it's loading that one. In other words my "tax_query" parameters appear to have no affect on the query. Am I not formatting the "tax_query" properly or am I missing something else?

I've also tried setting "tax_query" as below:

'tax_query' => array(
        'taxonomy' => 'video_type',
        'terms' => 'episode',
        'field' => 'slug',
    'include_children' => true,
        'operator' => 'IN'
),

but I'm still getting the same result.

41

The tax_query parameter is an array of arrays, not just an array.

This:

'tax_query' => array(
        'taxonomy' => 'video_type',
        'terms' => 'episode',
        'field' => 'slug',
        'include_children' => true,
        'operator' => 'IN'
),

Should instead be this:

'tax_query' => array(
    array(
        'taxonomy' => 'video_type',
        'terms' => 'episode',
        'field' => 'slug',
        'include_children' => true,
        'operator' => 'IN'
    )
),
  • 1
    Thanks Chip. I'm curious as to the reason why Wordpress has it built this way? – Josh Farneman Apr 16 '12 at 16:19
  • 3
    So that multiple tax queries can be performed, using Booleans. See the linked Codex entry, under the "Multiple Taxonomy Handling" section. – Chip Bennett Apr 16 '12 at 16:21
  • 1
    Worked like a charm for me! Thanks man, I was banging my head off the wall on this one! – Charles Blackwell Nov 23 '14 at 23:45
  • I can't seem to figure out how to translate this into a url parameter and have it actually used by WP_Query. It just keeps getting ignored. – realgeek Apr 12 '18 at 21:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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