I have a custom taxonomy and I wish to do a query for all custom posts who has no value assigned for that taxonomy (i.e. uncategorised).

This is what I have so far:

  $uncatQuery = new WP_Query( array(
                'post_type'         =>  'course',
                'tax_query' => array (
                        'taxonomy' => 'course_category',
                        'field' => 'name',
                        'terms' => '',
            ) );

However this does not work.

Please help!

NOTE: I manage to get it to work by creating a query to get all tax ids and then use a NOT IN operator, but that requires an additional query.

  • 1
    Do you have an 'Uncategorized' category? I believe you should.
    – mor7ifer
    Jan 31 '15 at 17:26
  • Not a bad idea, but how would I make it so when I create a course it will be default as this "uncategorized" course. The whole reason I'm doing this is so I can list all the courses my client forgot to put a category to (or not yet decided). Jan 31 '15 at 17:33
  • Did you try using the 'operator' parameter? You'll probably have to put all existing terms in 'terms'. codex.wordpress.org/Class_Reference/…
    – shanebp
    Jan 31 '15 at 17:35
  • 1
    I mean when you create a post of type 'course'. On save, check for terms and if none are found, assign it to uncategorized.
    – shanebp
    Jan 31 '15 at 19:14
  • 2
    There isn't a way to do it with WP_Query that doesn't involve either getting all term IDs first (as you mention), or modifying the SQL directly via filters. From a performance perspective the impact of the extra query is negligible, doing it with a single query just rolls the extra query into a single statement, but doesn't really reduce the amount of work the database is doing.
    – Milo
    Feb 1 '15 at 1:18

Okay thanks for all the helpful comments. It turns out there is no way to do this using WP_QUERY alone.

The best way I can think of is to do it is like so:

$taxIds = get_terms($options['post-types'][$this->current_post_type->name], array(
                'fields'        => 'ids',
            $uncategorisedQuery = new WP_Query( array(
                'post_type'         =>  $postType,
                'posts_per_page'    => -1,
                'tax_query' => array (
                        'taxonomy' => $taxonomyType,
                        'field' => 'term_id',
                        'terms' => $taxIds,
                        'operator' => 'NOT IN'
            ) );

Although @shanbp had a nice idea of creating a "Uncategorised" taxonomy and automatically applying it to each post on creation if no taxonomy is selected.

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.