Home > Tutorials > Wordpress > Display All Images Attached To A Post Without A Plugin
Permalink to Display All Images Attached To A Post Without A Plugin

Display All Images Attached To A Post Without A Plugin

by on 02.21.2010 | 40 comments

At first glance this looks pointless, just use the [gallery] shortcode, but there are times when you want more customization than the gallery shortcode allows for. In this tutorial we will look at how to get all the images attached to a post without a plugin.

You probably all know about my plugin The Attached Image which allows you to show any image attached to the current post. Well what about if you need to display all the images attached to a post? Gallery shortcode? Well, yes that will work, but what if you need to add in some custom coding?

The image on the right shows a wallpaper website I worked on. It runs on WordPress & uses the ideas I am going to share in this post to create the ‘Available Sizes’ section. Really it’s just an excuse to be lazy as the whole Wallpaper system is automated, upload your wallpapers & the script works out the sizes & lists them. However I’m sure that you lovely people can come up with other inventive uses for the same code. So here we go.

The Code

The code is actually just a couple of WordPress core functions used in a specific order, with a tad custom code.

<?php
$attachments = get_children(array('post_parent' => $post->ID,
						'post_status' => 'inherit',
						'post_type' => 'attachment',
						'post_mime_type' => 'image',
						'order' => 'ASC',
						'orderby' => 'menu_order ID'));

foreach($attachments as $att_id => $attachment) {
	$full_img_url = wp_get_attachment_url($attachment->ID);
        $split_pos = strpos($full_img_url, 'wp-content');
        $split_len = (strlen($full_img_url) - $split_pos);
        $abs_img_url = substr($full_img_url, $split_pos, $split_len);
        $full_info = @getimagesize(ABSPATH.$abs_img_url);
        ?>
        <div class="WallSizesHolder">
		<div class="WallSizesThumbHolder">
			<a href="<?php echo $full_img_url; ?>" title="<?php echo $attachment->post_title; ?>" target="_blank"><img src="<?php bloginfo('stylesheet_directory'); ?>/thumb.php?src=<?php echo $full_img_url; ?>&w=92&h=69&zc=1" /></a>
		</div>
		<p><?php echo $full_info[0].'x'.$full_info[1]; ?></p>
	</div>
<?php
}
?>

Let’s go through the code now & I’ll explain what is going on. First we use get_children to get all the posts (images) that are children of the current post, are an attachment, have image as their mime type & order them by their menu order (that’s the order set by the user in the gallery) or by ID if no menu order is set. This returns an array of objects, each object contains info about the attachment.

Now we run the $attachments variable through a foreach. One little note is that you cannot name the key variable ($att_id) $id as it will stop your comments from working properly (and probably other stuff). For each attachment we have, we grab the path to the full image using wp_get_attachment_url(). Now this is where the code you want to use comes in. I’ll continue to explain mine though just in case it inspires you. ;)

Next we take the url & find ‘wp-content’s position in the string. We then get the full length of the url & take it away from the position of ‘wp-content’. We then use substr() to cut the front of the string off (ending at ‘wp-content’). Now we use getimagesize() prepending ABSPATH to the front of our cut URL. ABSPATH holds the absolute (unix or windows) file path to the root of your WordPress install & as getimagesize() doesn’t always work on URLs depending on your server config, it’s generally always better to use the file path instead.

Finally we have the HTML I used. This is obviously going to change depending on what you are using it for, but we’ll go through the PHP I’ve used as it might be useful to your project. First we have some aesthetic divs then we open a hyperlink pointing to our full sized image. To fill in the title, for SEO, you can use $attachment->post_title which will hold the text written in the title field (if you haven’t changed it, it should be the images file name which is better than nothing). I’m using timthumb to dynamically alter the image size as you can see, finally I echo out the width & height retrieved by our trusty getimagesize().

That’s it. Stick a fork in me, I’m done. What you do with this is entirely up to you. I’m sure you can come up with something weird & wonderful that never even crossed my mind, but I hope it helps you in some way. If you do use code inspired by this tutorial in your project I’d love to see what you do with it. Just drop a link in the comments (if you want) and I’ll take a peek. ;)

As always if you have any problems or have any suggestions leave a comment & I’ll get back to you ASAP. Also if you want to see an active example of this working (rather than a picture), just visit Celeb O Rama Wallpapers & view any wallpaper. It’s the ‘Available Sizes’ bit like in the picture.

Written by Paul Robinson

A Web coder in languages such as CSS, X/HTML, jQuery, but mostly PHP. Addicted to Girls Aloud, Jennifer Morrison, Carah Faye Charnow, TV Show Chuck, and completely in love with Yvonne Strahovski's smile.

Give something back!

If you LOVED this tutorial and would like to show your appreciation, please consider or a little something from our Amazon Wishlist.

Discussion: 40 Comments

  1. Jun 28th, 2010 @ 20:26:35

    How would you specify the name of a specific post?


    • Jun 28th, 2010 @ 20:49:59

      I’m not sure what you mean? If you mean how would you get the images to a specific post, you would have to know it’s ID as you can’t get attachments via a post title (name) just in case there are two posts with the title.


    • Jun 28th, 2010 @ 23:36:12

      What would be the code to call the post by it’s ID?


    • Jun 28th, 2010 @ 23:47:28

      Nevermind I figured it out


  2. Aug 3rd, 2010 @ 15:26:11

    Hi! I used Your code to show images attached to a post, but it works not as it should be.

    If You have some free minute – please take a look at result page to find out what Im doing wrong.

    Test page – http://tusovka.in.ua/blog/games/11111111111/


  3. Aug 3rd, 2010 @ 20:47:42

    Thanx a lot dear friend!!!!
    It works for me now!

    Can I ask You one more question bout Your script tomorrow after Ill test some features?


    • Aug 3rd, 2010 @ 20:58:03

      Of course. Just throw any questions you have this way & I’ll try and answer them as best I can.


  4. Aug 3rd, 2010 @ 21:27:46

    Thx a lot for a support!

    Here’s a test article – http://tusovka.in.ua/blog/games/lorem-ipsum/

    So two questions:
    1. Is it possible to modify Your script for avoiding of showing last image attached? Cause this image is the main image of the article…

    2. Is it possible to make thumbnails not cropped to specified value “&w=92&h=69&” and to make it resize proportionally. For example longer side = 180 px.?


  5. Aug 3rd, 2010 @ 21:45:24

    2nd question is solved ;)


    • Aug 3rd, 2010 @ 22:14:11

      For this to work the main image will always have to be the last one.

      Add in this on line 8, that’s before the foreach starts:

      $last = end($attachments);
      

      Then place the next part inbetween line 9 & 10:

      if($last->ID == $attachment->ID) {
          break;
      }
      

      I’m unable to test that at the minute, but I think it should work. Let me know if you get any errors & I’ll fix them asap.


  6. Aug 4th, 2010 @ 07:45:42

    Works awesome!

    Thanx again!!!


    • Aug 4th, 2010 @ 08:20:42

      No problem, glad it worked & glad I could help you out. ;)


  7. Oct 4th, 2010 @ 18:24:41

    Hi,

    Thanks for the post but I can’t get the thumbs to show. I think this is because my theme doesn’t have a thumb.php file.

    Is this the problem and do you know where I can get the correct file. I tried using TimThumb PHP and renaming it to thumb.php but that didn’t work.

    Thanks,

    Dai


    • Oct 4th, 2010 @ 18:38:07

      Hi Dai,

      It is timthumb that is used on the wallpaper site. It should cause an error if it isn’t, but is GD available on your server?

      Have you checked to see if timthumb created a folder called ‘cache’. That’s where it places it’s created images. If you don’t have one, try creating the folder (in the same directory as timthumb) and make it writeable.

      That’s all I can think of that would stop timthumb from working properly. Hope it helps.


  8. Mar 21st, 2011 @ 16:54:34

    This was tremendously helpful. Thanks so much!


    • Mar 22nd, 2011 @ 14:11:20

      No problem Ruben. Glad it was helpful. :)


  9. Jun 12th, 2011 @ 03:11:14

    hello,

    your script is amazing! thanks!

    i just have one question: its possible to display only the first image attached?

    thanks in advance!


    • Jun 12th, 2011 @ 12:13:42

      Hi Bueno,

      Well it’s pretty easy since you already have all the attachments ordered by menu order (that’s the numbered order you set in the WordPress uploader). All you have to do is only access the first one instead of running the foreach.

      So to get the URL to the first image your code might look something like:

      <?php
      $attachments = get_children(array('post_parent' => $post->ID,
      						'post_status' => 'inherit',
      						'post_type' => 'attachment',
      						'post_mime_type' => 'image',
      						'order' => 'ASC',
      						'orderby' => 'menu_order ID'));
      
          $full_img_url = wp_get_attachment_url($attachments[0]->ID);
          //Whatever you want to do here...
      ?>
      

      As you can see you still need to pass it through the wp_get_attachment_url function. You just don’t need the loop as you only want the first item in the array.

      One thing to note. If you are wanting to use custom thumbnails and you want to grab a thumbnail size instead of the full size image you will need to use wp_get_attachment_image_src instead. The first parameter is the ID & the second is the name you gave to the thumbnail size when you set it up in your theme.

      That will return an array of which the URL to the image is in [0].

      Hope that helps.


    • Jun 13th, 2011 @ 19:15:50

      Hello Paul,

      Thank you for your quick response.
      I have a problem when i write something like:

      <img src="<?php bloginfo('template_directory'); ?>/thumb.php?src=<?php echo $full_img_url; ?>&w=70&h=70&zc=1" alt="" />

      into the area you said ‘Whatever you want to do here…’. doesn’t work.

      can you help me?

      thanks in advance!


    • Jun 13th, 2011 @ 19:32:54

      Sorry that was my fault. Using [0] won’t work as the key is the ID of the attachment. You’d need to do this instead.

      <?php
      $attachments = get_children(array('post_parent' => $post->ID,
      						'post_status' => 'inherit',
      						'post_type' => 'attachment',
      						'post_mime_type' => 'image',
      						'order' => 'ASC',
      						'orderby' => 'menu_order ID'));
          $attachment = current($attachments);
          $full_img_url = wp_get_attachment_url($attachment);
          //Whatever you want to do here...
      ?>
      

    • Jun 13th, 2011 @ 19:40:06

      Thank you for your amazing patience!
      As you can see i am a php-dumb…

      You can tell me whats wrong with my code?

      <?php
      					$attachments = get_children(array('post_parent' => $post->ID,
      					'post_status' => 'inherit',
      					'post_type' => 'attachment',
      					'post_mime_type' => 'image',
      					'order' => 'ASC',
      					'orderby' => 'menu_order ID'));
      					$attachment = current($attachments);
      					$full_img_url = wp_get_attachment_url($attachment);
      					//Whatever you want to do here…
      					<img src="<?php bloginfo('template_directory'); ?>/thumb.php?src=<?php echo $full_img_url; ?>&w=70&h=70&zc=1" alt="" />
      					?>
      

      This generate a error.

      Really thanks!


    • Jun 13th, 2011 @ 23:11:59

      Giving the error you get is always a good idea.

      From looking at the code though, you haven’t closed PHP wrote your image element & then reopened it.

      It should go like this:

      
      <?php
      $attachments = get_children(array('post_parent' => $post->ID,
      					'post_status' => 'inherit',
      					'post_type' => 'attachment',
      					'post_mime_type' => 'image',
      					'order' => 'ASC',
      					'orderby' => 'menu_order ID'));
      $attachment = current($attachments);
      $full_img_url = wp_get_attachment_url($attachment);
      ?>
      	<img src="<?php bloginfo('template_directory'); ?>/thumb.php?src=<?php echo $full_img_url; ?>&w=70&h=70&zc=1" alt="" />
      

    • Jun 14th, 2011 @ 14:17:04

      Paul,

      Thank you, i have a sintax error when i write the script to generate the thumb before the ?> (php closure tag), so the page stop loading.

      When i use the code you write (with the thumb code after the php closure tag) the timthumb dont recognize the $full_img_url parameter, so i have no image.

      So… i think it must be before, but i cant write it correctly. It must be just sintax stuff, but as say before, unfortunatly i cant do it.

      Thank you for your help and patience.


    • Jun 14th, 2011 @ 19:26:26

      Nope definitely outside. The syntax error is showing because it is finding an open PHP tag inside a PHP tag.

      The reason it’s not working is simply because I forgot to add a little bit to line 9 of the code I posted above. It should be:

      $full_img_url = wp_get_attachment_url($attachment->ID);
      

      I’ve just tested it on my local server & it works fine.


    • Jun 21st, 2011 @ 21:42:54

      it works!!!

      you´re a very good person paul robinson!!!

      thank you for you incredible patience!
      i ll make a donation soon!


    • Jun 22nd, 2011 @ 22:01:36

      Hi Bueno,

      No problem.

      Thank you for any donation are able to give, don’t forget if you don’t like to donate you can always buy me a present from my Amazon Wishlist instead, just click the wishlist button under any post.


  10. Oct 11th, 2011 @ 16:48:26

    Hi Paul,

    Thanks for the script.

    One question: How do I create a gallery page that just shows all the images in my media library?

    And can it be dynamic so that when I add an image to a post, that gallery page will automatically display that new image as well?

    Cheers
    James


    • Oct 11th, 2011 @ 18:07:59

      Hi James,

      You just don’t include the post_parent parameter as that tells it just to grab the images that below to a certain post. If you’ll want to add in numberposts though or it will pull back every single image in one go & if you have a lot (over 100) that could cripple your website.

      Anywhere you use this code it will automatically add the new one when you upload a new image without any modifications.


  11. Oct 11th, 2011 @ 19:41:59

    Hi Paul,

    Thanks for the quick response. Forgive me, I’m quite new to this so don’t quite follow. So basically is this the code:

    ‘inherit’,
    ‘post_type’ => ‘attachment’,
    ‘post_mime_type’ => ‘image’,
    ‘order’ => ‘ASC’,
    ‘orderby’ => ‘menu_order ID’));

    foreach($attachments as $att_id => $attachment) {
    $full_img_url = wp_get_attachment_url($attachment->ID);
    $split_pos = strpos($full_img_url, ‘wp-content’);
    $split_len = (strlen($full_img_url) – $split_pos);
    $abs_img_url = substr($full_img_url, $split_pos, $split_len);
    $full_info = @getimagesize(ABSPATH.$abs_img_url);
    ?>

    <a href="” title=”post_title; ?>” target=”_blank”><img src="/thumb.php?src=&w=92&h=69&zc=1″ />

    and do I click the HTML tab and just paste it in there?

    There’ll only be a maximum of around 50 images on my site so I think it’ll be alright as far as bandwidth is concerned.

    Thanks again
    James


    • Oct 11th, 2011 @ 23:09:00

      I’m afraid it’s not that simple (and your code got a little mangled by WordPress).

      You have to place it in a template file. There is an explanation of how to create them on the Codex as it would take to long to explain here in the comments. Although the easiest way is to copy the page.php or post.php file.

      It’s not the easiest thing to explain, sorry. I’m going to try and do some tutorials on how to do some basic things in WP like create new templates, but it’s hard to find time at the minute. :(


  12. Oct 12th, 2011 @ 08:36:45

    OK well thanks anyway Paul. I might leave it for now as I don’t want to mess up my site.

    Thanks again for your time and effort.

    James


    • Oct 12th, 2011 @ 14:02:24

      No problem James.

      If you want to test it you could always make the copy & assign the template to a draft or private page. That way no one but you can see it. ;)


  13. Dec 1st, 2011 @ 11:14:45

    Hi Paul,

    I’m using your technique to create a jflow slideshow on custom post types. I have it working pretty good, but I don’t want to use timthumb to resize. I have something like this built into my theme:

     echo get_the_post_thumbnail($id, 'bones-full-662', array('class' => 'alignleft')).'</a>';

    How would I call the function ‘bones-full-662′ to resize the thumbnail generated. I’m more of a front end guy thanks so much!


    • Dec 1st, 2011 @ 11:57:30

      Hi Greg,

      That function get_the_post_thumbnail() is a WP function used to get thumbnails from a list that have been predefined in your theme, generally in functions.php.

      If you want to use the size generated by ‘bones-full-662′ all you need to do is do this inside your post loop:

      the_post_thumbnail('bones-full-662', array('class' => 'alignleft'));
      

      You can of course change the class to whatever you like.

      If you want to add another thumbnail size you would need to add it to the list of sizes that WordPress needs to generate. You can do that using:

      add_image_size('unique-key', 100, 200, true);
      

      where ‘unique-key’ is a meaningful key you use when telling WP which thumbnail it should get. The two numbers are width & height respectively & the last bool is whether to hard crop the image or not.

      You would place that line next the the other add_image_size() function calls that are somewhere in your theme. Like I said, they are probably in functions.php.

      Once you’ve done that you will need to run a thumbnail regenerator plugin like the one by Viper007Bond. You only need to run it once, and then it can be deactivated & removed. This will run through all your previously uploaded images & create the newly created thumbnail size for each one.

      Hope that helps answer your question. If you have any problems please let me know. ;)


  14. Dec 1st, 2011 @ 13:07:19

    Thanks, Paul!

    That’s above and beyond, it really helped me grasp the concept better.

    I’m working on the site here http://idea-catalyst.co.za/Sandbox/Angela/v2/?post_type=portfolio&p=181

    It’s a sort of portfolio custom post type I created then it’s going to have a few shot of each piece of jewellery to scroll through. Using attached images to the post rather than a full blown gallery every time is a way more elegant solution I think.

    Cheers!


    • Dec 1st, 2011 @ 13:39:55

      No problem Greg. :)

      Looks like it should be great when you’ve got everything working. Using a post rather than a gallery is a great idea, especially when combined with a custom post type. Not only does it help organize the front end of things, but it helps make it really easy to add new items in the back end, brilliant if you have a client who may not be very tech savvy.


  15. Dec 9th, 2011 @ 17:15:47

    Thanks Paul, will give this a go :)


    • Dec 9th, 2011 @ 22:42:41

      No problem Martin, hope it works for you. :)


Leave a comment

Please enclose code in [lang] tags. For example [php] echo 'hello world'; [/php]

* Name, Email, Comment are Required