WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

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

I've been hunting around for a day for this answer and thought I should turn to StackExchange in the hopes someone has an aswer.

My goal is to display X images (for example, 4) in the sidebar of this one template, but I'd like it to be dynamic and either pull 4 random images, or the first or last 4 images in the gallery.

I'm currently using this code below to manually pull 4 images, but can someone provide code to be a bit more clever about it?

<?php echo do_shortcode('[gallery include="317,309,325" columns="1" link="file"]'); ?>
share|improve this question
up vote 0 down vote accepted

Sounds like you need a custom query in order to pull X amount of images. You could do the following (untested):


function custom_gallery_display( $number_of_images = 4 ) {

    //make sure you have access to the WPDB object
    global $wpdb;

    //pull 4 random attachments
    $images = $wpdb->get_results("SELECT ID from wp_posts WHERE post_type = 'attachment' ORDER BY RAND() LIMIT $number_of_images");

    //may need to tweak this;
    //not sure what format the results are returned
    $image_ids = implode( ',', $images );

    //now print with random images
    echo do_shortcode('[gallery include="' . $image_ids . '" columns="1" link="file"]');




That should do the trick, although it may need a bit of tweaking.

You should also check out the documentation http://codex.wordpress.org/Gallery_Shortcode

According to it, you can easily create the randomized order by setting the orderby attribute to RAND

<?php echo do_shortcode('[gallery include="317,309,325" columns="1" orderby="RAND" link="file"]'); ?>

However, if you are forced to use a custom query in order to use X amount of images, you may as well just randomize it at that point, as I did above in the query.

share|improve this answer
Btw, you could also use get_posts( $args ) to accomplish the custom query. Probably more efficient. – Chris Aug 8 '11 at 1:49
Thanks, Chris - I'll try those suggestions. – Andrew Aug 8 '11 at 3:10

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.