Query “Category A” + 1 post from “Category B” – how?

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:

Read More
$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.

Related posts

Leave a Reply

1 comment

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