I have a div and inside I wish display by random a post from category-a or a product from category-b. I’m looking for a query to do that.
I tried this:
<?php
$args = array(
'post_type' => array('product', 'post'),
'posts_per_page' => 1,
'cat' => 1,2,
'orderby' => 'RAND'
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
<article class="promo">
<div class="image">
<?php if (is_singular('product')){
echo 'Product';
}else{
echo 'Post';
}?>
</div>
</article>
<?php endwhile; ?>
Someone knows how to do that ?
thank you 🙂
EDIT CODE
<?php
$args = [
'post_type' => ['product','post'],
'posts_per_page' => -1,
'fields' => 'ids',
'post_type' => ['product','post'],
'posts_per_page' => 2,
'fields' => 'ids',
'tax_query' => [
'relation' => 'OR',
'taxonomy' => 'category',
'field' => 'slug',
'terms' => ['promo-distributeur', 'actu-distrib'],
'include_children' => false,
]
]
];
$posts_ids = get_posts($args);
$total = count($posts_ids);
if ($total > 0) {
$rnd = mt_rand(0, $total);
$pid = $posts_ids[$rnd];
$post = get_post( $pid);
while ( $post->have_posts() ) : $post>the_post(); global $product; ?>
<article class="promo">
<div class="image">
<?php if (is_singular('product')){
echo 'Product';
}else{
echo 'Post';
}?>
</div>
</article>
<?php endwhile;
} ?>