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"]'); ?>

1 Answer 1


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.

  • Btw, you could also use get_posts( $args ) to accomplish the custom query. Probably more efficient.
    – Chris
    Aug 8, 2011 at 1:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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