0

I have 2 post types (post and help). In post (post type), there is a category named "Hello" and I want to get all posts from the category "Hello" (post_type = post and category_id = 2) and all posts from the post type "help" with a uniq WP_Query.

This doesn't work:

$categoryId = 2;
$page = get_query_var('paged', 1);
$post_per_page = get_option('posts_per_page', 10);
$params = array(
    'post_type' => array('help', 'post'),
    'post_status' => array('publish'),
    'cat' => $categoryId,
    'paged' => $page,
    'posts_per_page' => $post_per_page,
    'orderby' => 'date', 
    'order' => 'DESC',
);

$q = new WP_Query($params);
  • What do you mean by This doesn't work? Do you get any error/no result? What is the exact issue? – Rohit Pande Jan 7 '16 at 13:44
1

A good way could be the one explained here

Basically you get the different queries results separately, assigning them to two different variables, merge the two result sets into array, getting the IDs of all this combined arrays, and last.. querying by IDs

$args1 = array(
  'post_type' =>   'help',
  'post_status' => 'publish'
  )
$args2 = array(
  'post_type' =>   'post',
  'cat' => $categoryId,
  'post_status' => 'publish'
)
$help_posts = get_posts( $args1 );
$post_posts = get_posts( $args2 );
$combined_query_array = array_merge ($help_posts, $post_posts ); //merge
$post_myneeded_IDs =  wp_list_pluck( $combined_query_array, 'ID' ) //squeeze IDs out
$desidered_query = get_posts( array(
  'post__in'    => $post_myneeded_IDs,
  'orderby'     => etc. etc
));

update, following the comments.. using 'fields' => 'ids'

$args1 = array(
  'post_type' =>   'help',
  'post_status' => 'publish',
  'fields' => 'ids'
  )  //now get_posts() will return just a collection of IDs
$args2 = array(
  'post_type' =>   'post',
  'cat' => $categoryId,
  'post_status' => 'publish',
  'fields' => 'ids'
  )
$help_posts_ids = get_posts( $args1 );
$post_posts_ids = get_posts( $args2 );
$combined_posts_ids = array_merge ($help_posts_ids, $post_posts_ids ); //merge
$desidered_query = get_posts( array(
  'post__in'    => $combined_posts_ids,
  'orderby'     => etc. etc
));
| improve this answer | |
  • You can use the 'fields' => 'ids' in get_posts() to only fetch the ids and to skip the wp_list_pluck() part. – birgire Jan 8 '16 at 13:11
  • yes, far more elegant :) – urka_mazurka Jan 8 '16 at 14:37

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.