I am trying to show some posts on a front page grid. For that I need to combine 2 queries. I want to show
a) all posts with 'post_type' => 'project'
AND
b) all posts with 'post_type' => 'post'
, which are 'category__not_in' => array(1,4,5,6,8)
, and which have the meta_key 'show_in_grid'
set to 1
They are displayed with random sorting all in one list
.
In the WordPress documentation for WP_Query
it says you can do for example:
$query = new WP_Query( 'meta_value=blue&post_type=page' );
but this doesn’t seem to work as expected.
If i do:
'post_type=post&meta_key=show_in_grid&meta_value=1'
it just ignores whether or not the key is set to 1 or not.
If i do:
'post_type' => 'post',
'meta_query' => array(
array( 'key' => 'show_in_grid',
'value' => '1',
'compare' => '=')),
then, everything works as expected.
Is this an error in the Documentation? And how can I have 2 different queries combined with a logical OR? I saw there is something like that for tax_query using ‘relation’.
Answer
Ok, i got it to work thanks to the comments here: http://wordpress.org/support/topic/multiple-queries-compiling-into-one-loop?replies=5#post-1929074
The final solution is this:
<?php
// first query
$blogposts = get_posts(array(
'category' => 5,
'post_type' => 'post',
'meta_query' => array(
array('key' => 'show_in_grid',
'value' => '1',
'compare' => '=')),
'post_status' => 'publish',
'posts_per_page' => 1000
));
// second query
$projects = get_posts(array(
'post_type' => 'project',
'post_status' => 'publish',
'posts_per_page' => 1000
));
$mergedposts = array_merge( $blogposts, $projects ); //combine queries
$postids = array();
foreach( $mergedposts as $item ) {
$postids[]=$item->ID; //create a new query only of the post ids
}
$uniqueposts = array_unique($postids); //remove duplicate post ids
$args = array(
'post_type' => array('project','post'),
'post__in' => $uniqueposts,
'orderby' => 'rand'
);
$loop = new WP_Query($args);
while ( $loop->have_posts() ) : $loop->the_post();?>
For some strange reason ‘post_type’ had to be specified in the original 2 queries AND the final query otherwise it wouldn’t work !?
Hope this helps someone.. 🙂