get_posts assigned to a specific custom taxonomy term, and not the term's children

  • Say I have the following taxonomy terms:

    Term 1
      Term 1.1
      Term 1.2
    Term 2
      Term 2.1
    

    How can I get only posts that are assigned to Term 1 and not include those that are assigned to Term 1.1 or Term 1.2?

    For example:

    $pages = get_posts(array(
      'post_type' => 'page',
      'numberposts' => -1,
      'tax_query' => array(
        array(
          'taxonomy' => 'taxonomy-name',
          'field' => 'id',
          'terms' => 1 // Where term_id of Term 1 is "1".
        )
      )
    );
    

    is also giving me posts that have Terms 1.1 and 1.2 assigned.

    Thanks.

  • In looking at the WP_Tax_Query class in /wp-includes/taxonomy.php, I found that there is a 'include_children' option which defaults to true. I modified my original get_posts() call with the following, and it works great:

    $pages = get_posts(array(
      'post_type' => 'page',
      'numberposts' => -1,
      'tax_query' => array(
        array(
          'taxonomy' => 'taxonomy-name',
          'field' => 'term_id', 
          'terms' => 1, /// Where term_id of Term 1 is "1".
          'include_children' => false
        )
      )
    ));
    

    List of more query parameters: http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

    Reading from the Codex page linked to, I think the value of 'field' in the tax_query array should be 'term_id' rather than 'id': "Possible values are 'term_id', 'name' and 'slug'. Default value is 'term_id'." I'm guessing 'id' only works because it causes a fall-back to the default.

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM