Query multiple post type and categories

The following code selects IDs of all posts type product and post, which belong to terms category-a or category-b, with taxonomy_01 and taxonomy_02, respectively.

$args = [
    'post_type' => ['product','post'],
    'posts_per_page' => -1,
    'fields' => 'ids',
    'tax_query' => [
        'relation' => 'OR',
        [
            'taxonomy' => 'taxonomy_01',
            'field' => 'slug',
            'terms' => 'category-a',
            'include_children' => false,
        ],
        [
            'taxonomy' => 'taxonomy_02',
            'field' => 'slug',
            'terms' => 'category-b',
            // OR by id
            //'field' => 'term_id', // default value
            //'terms' => 2,
            'include_children' => false,
        ],
    ]
];
$posts_ids = get_posts($args); 
$total = count($posts_ids);
if ($total > 0) { 
    $rnd = mt_rand(0, $total - 1);
    $pid = $posts_ids[$rnd];
    $my_post = get_post( $pid);
    // display post
}

I assume that the terms category-a, category-b belongs to different taxonomies. If not, then the tax_query should be:

'tax_query' => [
    [
        'taxonomy' => 'taxonomy_01',
        'field' => 'slug',
        'terms' => ['category-a', 'category-b'],
        'include_children' => false,
    ],
]

UPDATE
I changed variable in the above code from $post to my_post. Your code:

$args = [
    'post_type' => ['product','post'],
    'posts_per_page' => -1,
    'fields' => 'ids',
    'tax_query' => [
        'relation' => 'OR',
        [
            'taxonomy' => 'taxonomy_01',
            'field' => 'slug',
            'terms' => 'category-a',
            'include_children' => false,
        ],
        [
            'taxonomy' => 'taxonomy_02',
            'field' => 'slug',
            'terms' => 'category-b',
            // OR by id
            //'field' => 'term_id', // default value
            //'terms' => 2,
            'include_children' => false,
        ],
    ]
];
$posts_ids = get_posts($args); 
$total = count($posts_ids);
if ($total > 0) {
    // get random post_ID 
    $rnd = mt_rand(0, $total - 1);
    $pid = $posts_ids[$rnd];
    $my_post = get_post( $pid);

    // display post
    if ( !empty($my_post) ) : ?>

        <article class="promo">  
            <div class="image">
            <?php 
                if ( $my_post->post_type == 'product' )
                    echo 'Product';
                else
                    echo 'Post';
            ?>
           </div>  
       </article>
   <?php endif;
}

Leave a Comment