1

Background:

I'm trying to display images in a slideshow, and I want to select those pictures randomly from the website's media. The image has a custom field in order to be selected for being the slideshow.

I was able to figure all of that out, and I used a wp_query to find all of the images with the custom field that says it could be used in the slideshow.

Question:

Now my problem is how should I go about looping through the query to get to the post number I want?

Code:

$args = array(
   'post_type' => 'attachment',
   'meta_key' => 'on_front_page',
   'meta_value' => '1'
);
$wp_query = new WP_Query($args);
$total_images = (int) $wp_query->found_posts;
if ($total_image >= 6) {
    for ($i = 0; $i < 6; $i++) {
        rand(0, $total_images);
    }
} 
elseif ($total_image >= 6) {
    for ($i = 0; $i < $total_image; $i++) {
       rand(0, $total_images);
   }
 }

1 Answer 1

3

I think instead of using PHP rand you're better off limiting ( if you need to ) using posts_per_page and then getting a random set using orderby => 'rand'.

Full List of Ordering Parameters

So if I were to edit your query it would look like this:

$args = array(
   'post_type'  => 'attachment',
   'meta_key'   => 'on_front_page',
   'meta_value' => '1'
   'orderby'    => 'rand'
   'posts_per_page' => 6
);

$slides = new WP_Query($args);
$total_images = (int) $slides->found_posts;

if( $slides->have_posts() ) {
    while( $slides->have_posts() ) {
        echo $post->ID;  // The Attachment ID
    }
}
2
  • Does this make it that I only recieve 6 of the pictures in a random order?
    – benj rei
    Commented Jan 26, 2015 at 22:58
  • Yes it does! You can view the link in my answer for more information.
    – Howdy_McGee
    Commented Jan 26, 2015 at 22:59

Your Answer

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

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