0

Is there a way to query posts from multiple post_type's and filter the normal blog posts by a category?

I am trying to display the 10 latest custom_post_type posts and blog posts on my homepage in a single query - so that I have 10 posts in total, sorted by post_date in DESC order, containing all posts from my custom_post_type and blog posts from a certain category.

Let's say I have custom post type called news. I want to query both news and posts, but limit posts to category with id 3. I do NOT want to limit news to any category.

$args = array (
    'cat' => 3,
    'post_type' => array ( 'news', 'post' )
);

The above code seems to only work half - it only fecthes blog posts from the category 3, but no custom_post_types at all...

2
  • your custom post needs category with id=3 assigned, to get into results.
    – Amit Kosti
    Commented Aug 3, 2012 at 12:58
  • Is the category taxonomy registered to the custom post type? Please add your post type and taxonomy registration code to the question so others can better assist you.
    – t31os
    Commented Feb 3, 2014 at 19:55

2 Answers 2

0

That should work. Make sure there're no typos in your custom post type name or where you register the post type.

If that fails try using:

'post_type' => 'any'
4
  • Well, it doesn't and I think I now why: Wordpress filters also custom_post_type based on the category ID, and since no custom_post_type post has that category attached to it, it doesn't return any.
    – ragulka
    Commented Apr 5, 2012 at 9:04
  • Yeah that would do it! Do you want to change your question to 'How can I register the category taxonomy for custom post types?' because I can answer that... Commented Apr 5, 2012 at 9:23
  • Wait, that makes no sense - maybe I wasn't clear: Let's say I have custom post type called news. I want to query both news and posts, but limit posts to category with id 3. I do NOT want to limit news to any category.
    – ragulka
    Commented Apr 5, 2012 at 12:44
  • Ah ha. In that case you probably need to do a custom query. Not sure if there's an easy way to combine 2 queries with only one WP_Query call... Commented Apr 6, 2012 at 13:13
0

WordPress query logic is aimed at retrieving single set of posts, satisfying all the query conditions. What you want is combination of two different sets of posts.

One of the way to accomplish that would be querying for IDs of posts ( 'fields' => 'ids' ) in each set and then combine them to use as post__in argument for final query.

To do this in one query precisely will require modifying raw underlying SQL and is much less convenient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.