3
votes

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.

2
As suggested below, I've added the following line: <?php echo $GLOBALS['nextSundayTalkQuery']->request; ?> This returns: SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND 0 = 1 AND wp_posts.post_type = 'talk' AND (wp_posts.post_status = 'publish' OR wp_posts.post_author = 1 AND wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 1 - Pete G
I suspect that the "1=1 AND 0=1" might be a problem, but if so I'm not sure what this refers to or what's causing it. - Pete G
cool - I wonder if it is anything to do with taxonomy being named talk-type so theres a collision - check if you shouldnt be using underscore, perhaps? e.g. talk_type - Luke Barker
extra bit of help - check the specific Wordpress stackexchange, and in particular try this link, which gives a nice example of taxonomy query: wordpress.stackexchange.com/questions/49185/… POst your question there it might get better insights! - Luke Barker
Thanks - I'll take a look. I have seen that link before, but I seem to be making the queries correctly. Unfortunately changing the taxonomy to "talktype" didn't help! - Pete G

2 Answers

5
votes

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

1
votes

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.