skip to Main Content

On my website, there are a couple of custom post types with default blog posts. On the blog posts, there are many categories.

One of the post types is webinar. I like to query all posts from the post type webinar and those blog posts that have category id 43

I tried following way but does not work.

1:

$query = new WP_Query(array(
  'post_type' => array('webinar'), // I need all post from webinar
  'cat' => '43', // I need all blog post under this category (Post type post category id 43)
);

Result: No post found

2:

$query = new WP_Query(array(
  'post_type' => array('webinar','post'), // I need all post from webinar
  'cat' => '43', // I need all blog post under this category (Post type post category id 43)
);

Result: Only posts of category id 43, no post from post types webinar

I need something like the following:

$query = new WP_Query(array(
  array(
    'relation' => 'OR',
    array(
      'post_type' => array('webinar')
    ),
    array(
     'post_type' => 'post',
     'cat' => '43'
    )
  )
));

How can I do this?

3

Answers


  1. $posts = get_posts([
      'post_type' => 'webinar',
      'post_status' => 'publish',
      'numberposts' => -1
       
    ]);
    
    Login or Signup to reply.
  2. $post_data = get_posts( [
        'post_type' => ['webinar', 'post'],
        'posts_per_page' => - 1,
        'tax_query' => array(
           'taxonomy' => 'category',
           'field'    => 'term_id',
           'terms'    => '43'
         ),
    ] );
    

    Would something like this work? I have not tested this so may need playing with a bit.

    If you dont want to use get_posts then can always use new WP_Query but will need to ammend

    Login or Signup to reply.
  3. Solution 1

    // This could be cached in the site option
    // in case this code will take a long time.
    $webinar_terms = get_terms([
        'taxonomy' => '{webinar_tax_name}',
        'hide_empty' => true,
    ]);
    
    $allowed_terms_ids = [];
    
    foreach ( $webinar_terms as $term )
    {
        $allowed_terms_ids[] = $term->term_id;
    }
    
    // Add post cat to allowed terms.
    $allowed_terms_ids[] = 43;
    
    $query = new WP_Query([
      'post_type' => ['webinar','post'],
      'cat' => $allowed_terms_ids,
    ]);
    

    NOTE

    This will work only in case all webinar posts will be assigned to at least 1 {webinar_tax_name} term.

    Solution 2

    You may use posts_request hook and update SQL for 1 of your queries in your example. But I would prefer 1st solution as it will be more clear for other devs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search