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.

<?php //The Query. You can do whatever you want here. query_posts('cat=1&showposts=5&orderby=title&order=ASC'); //The Loop if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php // get the pot meta data. We want the images so "thumb" as a parameter. $thumb = get_post_meta($post->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; } } } ?> <img alt="<?php the_title() ?>" src="<?php echo $thumb; ?>" /> <?php endwhile; endif; ?>
8 comments

Leave a Reply

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

*
*