Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

Answer:

$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' );
                }
            }
            wp_reset_query();
share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

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

http://codex.wordpress.org/Function_Reference/get_children

For instance:

$images = get_children( array(
              'orderby' => 'rand',  <------this is random param for your array
              'post_type' => 'attachment',
              'post_mime_type' => 'image')
        );           
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. –  Thorn007 Mar 28 '11 at 0:19
1  
your post and this one fix the issue stackoverflow.com/questions/2640520/… –  Thorn007 Mar 28 '11 at 0:46
add comment

Your Answer

 
discard

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.