A fresh mix of code snippets and tutorials

Display all images attached to post

Another technique for working with WordPress attachments, here’s how to display all images that are attached to the post, either before or after the existing post content.

For example, if you are using my User Submitted Posts, the following code will display all of the attached images to the post content. Add this to your theme’s functions.php file:

// display user-submitted images
function usp_display_images($content) { 
     global $post;
     $args = array('order'=>'ASC', 'post_type'=>'attachment', 'post_parent'=>$post->ID, 'post_mime_type'=>'image', 'post_status'=>null); 
     $items = get_posts($args); ?>
          <div class="usp-image">
          <?php foreach ($items as $item) {
               $atts = wp_get_attachment_image_src($item->ID, 'medium');
               $full = wp_get_attachment_image_src($item->ID, 'full'); ?>
               <a href="<?php echo $full[0]; ?>"><img src="<?php echo $atts[0]; ?>" width="<?php echo $atts[1]; ?>" height="<?php echo $atts[2]; ?>" alt=""></a>
          <?php }
               $author = get_post_meta($post->ID, 'user_submit_name', true);
               $url = get_post_meta($post->ID, 'user_submit_url', true);
               if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
               echo '<span class="usp-author-link">Posted by <a href="' . $url . '">' . $author . '</a></span> ';
          } ?>
<?php return $content; 
add_filter('the_content', 'usp_display_images');

One spiffy thing about this technique is that there’s no editing required. Just drop it in and good to go. Of course, you’ll want to style with CSS and possibly customize the PHP/HTML to suit your needs.

You may also be interested in my tutorials for setting attachments as featured images and displaying images with User Submitted Posts. It’s just good times.

Update! User Submitted Posts now features options to auto-display content, including images and other fields. Check out the plugin settings and documentation for more information. So you can auto-display all attached images without messing with any code :)

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress