WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How to add a random image to a post from gallery and only show one?

I know how to add an image and a gallery. I need to have one image from the galley show on the page at random each time the page is loaded.

The page should only show one image at a time.

Is there a plugin or short code to do this? I know how to make gallery's random, but they show all the images.


$args = array( 
                'post_type' => 'attachment',
                'numberposts' => 1,
                'orderby' => 'rand',
                'post_status' => null,
                'post_parent' => get_the_ID(),
                'post_mime_type'  => 'image'
            have_posts(); //must be in the loop
            the_post(); //set the ID

            $images = get_children( $args );            

            if ($images) {
            foreach ( $images as $attachment_id => $attachment ) {
                    echo wp_get_attachment_image( $attachment_id, 'full' );
share|improve this question
up vote 3 down vote accepted

You should use the 'orderby' => 'rand' parameter for the get_children() attachments function.

For instance:

$images = get_children( array(
    'orderby'        => 'rand',       // this is random param
    'post_type'      => 'attachment',
    'post_mime_type' => 'image',
    'post_parent'    => get_the_ID(),
share|improve this answer
this works but adds image from the library and not the gallery. I need it to be from the gallery so each set differs from page to page. – Kevin D. Mar 28 '11 at 0:19
your post and this one fix the issue stackoverflow.com/questions/2640520/… – Kevin D. Mar 28 '11 at 0:46

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.