So you want to query posts from multiple post types, but also with different query-arguments like custom field, tax_query or categories.
As you did not post what you tried, have already or want to have, please try something like this:
We are using 3 queries to set everything up. You can add different arguments to each query.
Get post ID´s
from our first post type, product
:
$first_post_ids = get_posts( array(
'fields' => 'ids', // only return post ID´s
'posts_per_page' => '5',
'post_type' => array('product'),
));
Get post ID´s
from our second post type, post
:
$second_post_ids = get_posts( array(
'fields' => 'ids', // only return post ID´s
'posts_per_page' => '5',
'post_type' => array('post'),
));
Merge our two queries into one:
$merged_post_ids = array_merge( $first_post_ids, $second_post_ids);
Build the third query:
$wp_query = new WP_Query( array(
'post_type' => 'any', // any post type
'post__in' => $merged_post_ids, // our merged queries
) );
The loop:
if ( $wp_query->have_posts() ) :
while ( $wp_query->have_posts() ) : $wp_query->the_post();
//look at $post here !!
//Example: $post->post_type;
//this return the type of each post so you can do checks and stuff
//for example show title and content
the_title( '<h2>', '</h2>' );
the_content();
endwhile;
// reset after query
wp_reset_query();
else :
echo 'Sorry, no posts matched your criteria.';
endif;
Update: Check if array_merge is not null to prevent any types showing
array_merge
is used to merge 2 arrays, like the name suggests.
So for example, if $first_post_ids
is a string
, than it will not work. Thats why we use 'fields' => 'ids',
in our queries.
Because as the Codex says:
‘ids’ – Return an array of post IDs.
And even if one of these two queries is empty (i.e. we have no posts), array_merge
will still work.
But yes, we can check array_merge
:
//... first two queries
$merged_post_ids = array_merge( $first_post_ids, $second_post_ids );
//check if the array_merge exists/not null
if ( $merged_post_ids ) {
$wp_query = new WP_Query( array(
'post_type' => 'any', // any post type
'post__in' => $merged_post_ids, // our merged queries
) );
//... your query code here
}//END if $merged_post_ids
You can also expand it with an else
statement to let another query run.