How to get random post attachments WordPress

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


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


<?php the_title() ?>

About Rick

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

Leave a Reply

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