“tax_query” parameter not working with WP_Query

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?

Read More

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.

Related posts

Leave a Reply

2 comments

  1. 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'
        )
    ),
    
  2. It’s also worth to pay attention if you are formatting the rules correctly:

    new WP_Query([
        'post_type' => 'vehicle',
        'tax_query' => [
            'relation' => 'OR',
            [
                'taxonomy' => 'brand',
                'field' => 'slug',
                'terms' => 'bmw',
            ],
            [
                'taxonomy' => 'brand',
                'field' => 'slug',
                'terms' => 'mercedes',
            ]
        ],
    ]);
    

    This way you are fetching vehicles that have brand bmw OR mercedes.

    If you want to fetch vehicles that have brand bmw AND mercedes:

    new WP_Query([
        'post_type' => 'vehicle',
        'tax_query' => [
            [
                'taxonomy' => 'brand',
                'field' => 'slug',
                'terms' => ['bmw', 'mercedes'],
            ],
        ],
    ]);