1

It's pretty easy to query posts from one category but what if I need also one single post from another category?

$query = new WP_Query( 'cat=4' );

I'm looking for something like this:

$query = new WP_Query( array( 'cat' => 4, 'post__in' => array( 20 ) ) );

But the above code will not return anything because there are not posts with an ID of 20 in category 4. I'm wondering if anyone has any idea how this could be done.

2

I don't see a way to do this with WP_Query alone. However...

function posts_where_add_post_wpse_96030($where) {
  global $wpdb;
  return $where." OR {$wpdb->posts}.ID = 1";
}
add_filter('posts_where','posts_where_add_post_wpse_96030');
$query = new WP_Query( 'cat=9' );

That will alter the query everywhere it runs so you will need to add conditions to the callback so that $where is only altered where you want it to be. For example...

function posts_where_add_post_wpse_96030($where) {
  global $wpdb;
  if (is_home()) {
    $where .= " OR {$wpdb->posts}.ID = 1";
  }
  return $where; 
}

Now the query will only be altered when it runs on a page where is_home is true. I don't know what conditions you need. You didn't include that in your question so you will have to work that out yourself.

  • Thank you for your reply! I was only wondering if this is easily doable and if I'm missing something obvious. So, if there is no nice solution then I think I'll list all posts that belong to "Category A", add one more post and use post__in - looks simpler for what I want to do. Thanks again! – Paul Apr 16 '13 at 15:59
  • I would consider a post_where solution to be a "nice" solution, but its your call. – s_ha_dum Apr 16 '13 at 16:01

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.