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.

I'm developing a photo gallery WP site. I would like to add "ul" list of images that are randomly picked from the gallery.

How would I randomly pick a number of images from the media library.

Any pointers would be greatly appreciated.

share|improve this question
add comment

1 Answer

Adding the following to your theme's functions.php file will let you use a shortcode ( [wpse73055-random-images] ) with an optional num parameter (i.e. [wpse73055-random-images num=5] to display 5 random images).

function wpse73055_get_random_images( $atts ) {
    extract( shortcode_atts( array(
        'num' => 10
    ), $atts ) );

    $args = array(
        'post_type' => 'attachment',
        'post_mime_type' =>'image',
        'post_status' => 'inherit',
        'posts_per_page' => $num,
        'orderby' => 'rand'
    );
    $images_query = new WP_Query( $args );

    $images = $images_query->posts;

    $output = '<ul>';
    foreach ( $images as $image ) {
        $output .= '<li>' . wp_get_attachment_link( $image->ID ) . '</li>';
    }
    $output .= '</ul>';

    return $output;
}
add_shortcode( 'wpse73055-random-images', 'wpse73055_get_random_images' );
share|improve this answer
1  
Querying for all posts is risky (simply put - what if there is million of images? instantly fried server). Would be better to 'orderby' => 'rand' to fetch limited randomized set at database stage. –  Rarst Nov 18 '12 at 18:01
    
That was a bit daft indeed. Edited. Would not have minded, had you done so in the first place. –  Johannes Pille Nov 18 '12 at 18:09
2  
Some evenings I am like immaterial ghost that barely has enough left in it to wail at mortals so they fix their stuff. :) –  Rarst Nov 18 '12 at 18:14
    
I've added the above code to the functions.php and used [wpse73055-random-images] where I would like the images. I'm not getting any images - is there anything else I should be doing. –  user668499 Nov 18 '12 at 22:25
    
Got it working now put the images are low quaintly. How would I control which size image is used? –  user668499 Nov 19 '12 at 10:41
show 1 more 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.