2

When I call WP_Query with tax query or category__in, I get posts only from first category in array of requested categories.

$query = new WP_Query(
    array(
        "tax_query" => array(
            array(
                "taxonomy" => "category",
                "field" => "term_id",
                "terms" => array(1, 2, 3)
            )
        ),
        "posts_per_page" => -1
    )
);

Here is sql query from $query->request:

SELECT wp_posts.*
FROM wp_posts
INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
INNER JOIN wp_term_relationships AS tt1 ON (wp_posts.ID = tt1.object_id)
INNER JOIN wp_term_relationships AS tt2 ON (wp_posts.ID = tt2.object_id)
WHERE 1=1
  AND (wp_term_relationships.term_taxonomy_id IN (1,
                                                  2,
                                                  3)
       AND tt1.term_taxonomy_id IN (1)
       AND tt2.term_taxonomy_id IN (1))
  AND wp_posts.post_type = 'post'
  AND (wp_posts.post_status = 'publish'
       OR wp_posts.post_status = 'future'
       OR wp_posts.post_status = 'draft'
       OR wp_posts.post_status = 'pending'
       OR wp_posts.post_status = 'private')
GROUP BY wp_posts.ID
ORDER BY wp_posts.post_date DESC

Results list only posts in category 1. What is wrong with my query?

  • What happens if you use 'id' instead of 'term_id' for 'field'? – Chip Bennett Apr 7 '14 at 14:27
  • I get same results with 'id'. – user3256672 Apr 7 '14 at 14:29
  • Do they happen to be posts that are in all three categories? – Chip Bennett Apr 7 '14 at 14:34
  • I have several posts, one in all categories one in 1 (uncategorized) and few more in 2 and 3. Result is correct but only gives post in first category. If I set categories to (2, 3, 1) it will return only posts with category 2. – user3256672 Apr 7 '14 at 14:42
  • Also sql AND tt1.term_taxonomy_id IN (1) 1 changes to first in "terms" array. – user3256672 Apr 7 '14 at 14:43
2

Found problem. I replaced:

$posts = $query->get_posts();

with:

$posts = array();
if ($query->have_posts()){
  while ($query->have_posts()){
    $query->next_post();
    array_push($posts, $query->post);
  }
}

And everything is working now.

| improve this answer | |

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.