Reputation: 133
I've been tearing my hair out a little trying to get tax_query working in my WP_Query. The code is as follows:
$nextSundayTalkArgs = array(
'post_type' => 'talk',
'posts_per_page' => 1,
'tax_query' => array(
array(
'taxonomy' => 'talk-type',
'field' => 'slug',
'terms' => 'sunday-talk'
)
)
);
$nextSundayTalkQuery = new WP_Query( $nextSundayTalkArgs );
There are definitely posts with the post type of "talk" - if I remove the tax_query part, the correct posts display just fine. There are 5 talks with the correct taxonomy term of "sunday-talk" (and it doesn't work if I try to use IDs instead of slugs, either).
Bizarrely, if I change the post type to "post" and the taxonomy to "category", and leave out the "field" and "terms" part, it comes back with my only post to have no terms on it at all.
Any help greatly appreciated, before I go insane.
Upvotes: 3
Views: 12043
Reputation: 55
In your tax_query
, try setting field
to term_taxonomy_id
and using $term->term_taxonomy_id
instead of $term->term_id
:
$args = [
'post_type' => 'post',
'post_status' => 'publish',
'tax_query' => [
[
'taxonomy' => 'my_custom_taxonomy',
'field' => 'term_taxonomy_id',
'terms' => $term->term_taxonomy_id,
]
]
];
$query = new WP_Query($args);
Upvotes: 0
Reputation: 133
Eventually found the answer with some help on Wordpress Stackexchange. Still not 100% sure what I was doing wrong, but seemed to be a problem both with my functions layout and the post loop I was using in index.php
.
For anyone who comes across this question and is interested:
https://wordpress.stackexchange.com/questions/84607/custom-taxonomy-and-tax-query
Upvotes: 5
Reputation: 915
I am not sure of your answer, but I would first off try and work out what database query your code produces.
https://wordpress.stackexchange.com/questions/4809/how-to-display-sql-query-that-ran-in-query
This is a link to various ways of debugging a query. It helps a great deal as you see what it does, can run it on phpmyadmin etc.
Upvotes: 1