Custom taxonomy query that excludes children posts
-
I have been looking through the codex and forums and have not been successful in finding a solution. I feel like I am so close, but then again, I could be wrong.
I am querying to get a list of posts that are of a custom type (document-tutorial) that are in a custom taxonomy (document-category).
I can produce a list that matches but it includes posts that are in the children document-category but not not in the parent.
Example: Document Category of “Windows” has sub-cats of “Windows XP”, “Windows Vista” and “Windows 7”. When I ask for ones in “windows” I am getting items that are in the children categories.
I know this is a default behavior (at least that seems to be what I found), but I want to exclude the posts that are in children cats.
I have 2 code chunks that I have tried. This example produces a result that is as described above (everything in “parent-category” and its children).
$wpq = array( 'post_type' => 'document-tutorial', 'taxonomy' => 'document-category', 'term' => $doc->slug, 'orderby' => 'title', 'order'=>ASC, 'posts_per_page'=>-1, );
This is passed to $docposts = new WP_Query ($wpq); and then process through the loop. I can see if I pull the “request” element that the resulting SQL query has the array of taxonomy_term_id’s that are the parent and its children. It looks like this:
SELECT wp_posts.* FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (39,40,41,42) ) AND wp_posts.post_type = 'document-tutorial' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_title ASC
I would love to be able to pass in those ID’s and it should in theory solve it. So, I attempted a different request that uses a tax_query argument as per here – https://codex.www.ads-software.com/Function_Reference/query_posts#Taxonomy_Parameters
That code looks like this:
$wpq = array( 'post_type' => 'document-tutorial', 'orderby' => 'title', 'order'=>ASC, 'posts_per_page'=>-1, 'tax_query'=> array( 'taxonomy' => 'document-category', 'field' => 'term_taxonomy_id', 'terms' => array($term_tax_id), 'include_children' => false ) );
That produces and empty set and the “term_relationships” part in the above query is not included in the request.
I feel like I am missing something in the tax_query setup or some other means to show items that are only in the term I want.
Any help would be appreciated.
- The topic ‘Custom taxonomy query that excludes children posts’ is closed to new replies.