0

I have a some categories and want to get the posts with those categories:

$temp = $wp_query; // assign ordinal query to temp variable for later use  
$wp_query = null;

$wp_query = new WP_Query('cat=85'); 
if($wp_query->have_posts()) {   
    ...
}

But it is not entering in the if condition. The category with id=85 exists and some posts are using it. So I don't understand why it is not returning any post.

Any idea. Am I doing something wrong?

4
  • 1
    There is nothing wrong with what you are doing. This will work with a valid ID with posts assigned to it. Are you trying to get posts from a CPT, perhaps?
    – s_ha_dum
    Commented Jan 21, 2014 at 15:23
  • @s_ha_dum - Sorry, CPT?
    – Manolo
    Commented Jan 21, 2014 at 15:27
  • Custom Post Type
    – s_ha_dum
    Commented Jan 21, 2014 at 15:29
  • @s_ha_dum - Oh! Yes. This is the problem. But I want to get all custom posts. Any way to achieve it?
    – Manolo
    Commented Jan 21, 2014 at 15:30

1 Answer 1

1

By default WP_Query will return only the post post type. To retrieve other post types, you need to add a post_type argument. Using any will return results from all public, registered post types.

$my_query = new WP_Query(
  array(
    'cat' => 1,
    'post_type' => 'any'
  )
); 
var_dump($my_query->request); // debug; allows you to see the SQL
if($my_query->have_posts()) {   
  // ..
}

If you only want a particular post type, just use the post type's slug, or you can use an array of post type slugs to get returns from multiple particular post types.

Also, there is rarely a good reason to clobber $wp_query, even if you save it to put it back later.

1
  • Of course! Thank you. I'm using an Ajax call, this is why the $wp_query.
    – Manolo
    Commented Jan 21, 2014 at 15:41

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.