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'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
add comment

1 Answer

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):

<?php

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

    return;

}

?>

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
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.