How to get random post attachments WordPress

Get random post attachments from WordPress posts (e.g image attachments).

Functions

I'm going to use the following functions. You can add, remove or change parameters if you wish to:

Full Code

Straightforward code with comments.


ID, 'thumb', $single = true);

if($thumb == ""){
// lets get the type image and fully RANDOM.
$attachments = get_children( array(
'post_parent' => $post->ID,
'numberposts' => $repeat,
'post_type' => 'attachment',
'orderby' => 'rand',
'post_mime_type' => 'image')
);

foreach ( $attachments as $att_id => $attachment ) {

// put the image in a array
$my_thumb = wp_get_attachment_image_src($att_id, $size, true);

// the [0] position goes for the image URL
$thumb = $my_thumb[0];

// I just want 1 image, so break it if the width is bigger than 800px
if($my_thumb[1]>800){
break;
}
}

}

?>
<?php the_title() ?>

8 comments

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*