Show posts from query randomly

I have this query –

<?php if( is_page_template('taxonomy-listing_area-channel.php') ) { ?>
<?php
            $posts = get_posts(array(

    'post_type'     => 'adverts',
    'numberposts'   => 1,
    'order'         => 'random',

    'meta_query'    => array(
        'relation'      => 'AND',
        array(
            'key'       => 'associate_adverts',
            'value'     => '204',
            'compare'   => 'LIKE',
        )
    ),
));

        ?>

<?php //if it's returning the object

foreach($posts as $advert){

 $img = get_field("top_advert", $advert->ID);?>

 <img src="<?php echo $img["url"]; ?>"/>

<?php }?>

But for somr reaosn the posts are just showing as the last one entered and now randomly, I’ve never had this problem before but I have no idea where I’m going wrong, and help would be much appreciated!

Related posts

Leave a Reply

3 comments

  1. You need to change this

    'post_type'     => 'adverts',
    'numberposts'   => 1,
    'order'         => 'random',
    

    To

    'post_type'        => 'adverts',
    'posts_per_page'   => 1,
    'orderby'          => 'rand',
    

    Now you code will look like

    <?php if( is_page_template('taxonomy-listing_area-channel.php') ) { ?>
    <?php
                $posts = get_posts(array(
    
     'post_type'        => 'adverts',
     'posts_per_page'   => 1,
     'orderby'          => 'rand',
    
        'meta_query'    => array(
            'relation'      => 'AND',
            array(
                'key'       => 'associate_adverts',
                'value'     => '204',
                'compare'   => 'LIKE',
            )
        ),
    ));
    
            ?>
    
    <?php //if it's returning the object
    
    foreach($posts as $advert){
    
     $img = get_field("top_advert", $advert->ID);?>
    
     <img src="<?php echo $img["url"]; ?>"/>
    
    <?php } }?>
    

    Also you forgot to close you if statement.