1

I want to show a random image from a few options in my loop if a custom field hasn't a certain value, or it could be if it had no thumbnail. In any case, it should spit out one of the random images. Instead it's giving me all of them for each post that satisfies the condition. How can I make it show just one at random? Thanks. Here's the code partial:

<?php

    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
    ?>

    <?php $image = get_post_meta($post->ID, 'myimage', true); ?>

    <?php if ($image != 'myimage.jpeg'){
        $upload_dir = wp_upload_dir();
        echo '<img class="myclass" src="'.$upload_dir['url'].'/'.$image.'" alt="">';
    } else { 
    ?>

    <?php 
    for ($i = 1; $i < 4; $i++) { ?>
    <?php echo 'defaultImage'.$i .'.jpeg';

    } ?>

    <?php

    $settings = get_option( "defaultImage" ); 
    $random = rand( 1, 4 );

    if ( isset( $settings[ "defaultImg$random" ] ) )
    echo $settings[ "defaultImg$random" ]; 

    }
?>

SOLVED: My solution was really simple:

$input = array("defaultImage1.jpeg", "defaultImage2.jpeg", "defaultImage3.jpeg", "defaultImage4.jpeg", "defaultImage5.jpeg", "defaultImage6.jpeg");
$upload_dir = wp_upload_dir();
$rand_keys = array_rand($input, 2);
echo '<img class="story-carousel" src="'.$upload_dir['url'].'/'.$input[$rand_keys[0]].'" alt="">';
0

My solution was really simple:

$input = array("defaultImage1.jpeg", "defaultImage2.jpeg", "defaultImage3.jpeg", "defaultImage4.jpeg", "defaultImage5.jpeg", "defaultImage6.jpeg");
$rand_keys = array_rand($input, 2);
echo '<img class="story-carousel" src="'.$upload_dir['url'].'/'.$input[$rand_keys[0]].'" alt="">';

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.