Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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...

share|improve this question
    
your custom post needs category with id=3 assigned, to get into results. –  amit Aug 3 '12 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 Feb 3 at 19:55

2 Answers 2

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'
share|improve this answer
    
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 Apr 5 '12 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... –  sanchothefat Apr 5 '12 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 Apr 5 '12 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... –  sanchothefat Apr 6 '12 at 13:13

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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