Show Images Attached To A WordPress Post Without Plugins

/ Wordpress / by Paul Robinson / 55 Comments
This post was published back on August 13, 2013 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

Here is a very quick, and very useful WordPress code snippet. To use this just place it in whichever template file you need to use it within. If you plan to use it a lot you can place the code in a separate file and just use get_template_part() to include it when you need it. Snazzy!

Show Attached Images Without Plugins

This code is actually just a couple of WordPress core functions used in a specific order. That’s what makes it ingeniously simple.

That’s it. Like I said, quick but exceptionally handy. All you need to do is swap medium on the highlighted line for whichever image size you want. WordPress has full, large, medium, and thumbnail available as default. You can also call any sizes you have registered with add_image_size(). This can also be used to get other media, just change image to the media type you’d like (line 2). For example video will get uploaded videos.

55 Comments

Author’s gravatar

How would you specify the name of a specific post?

Reply
Author’s gravatar author

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.

Author’s gravatar

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

Author’s gravatar

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/

Reply
Author’s gravatar author

Hi,

The code seems to be working okay. The reason your images don’t work is because your path looks like this:

The image url

Gets us to the image fine. However

Gives a 404.

My advice would be to triple check the path to your thumb.php file as it seems to be incorrect.

Hope that helps.

Author’s gravatar

Quadruple checked path to thumb.php and found that it is missing 🙂
Ill try to find some thumb.php from other theme and put it in the place 🙂

Author’s gravatar

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?

Reply
Author’s gravatar author

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

Author’s gravatar

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.?

Reply
Author’s gravatar

2nd question is solved 😉

Reply
Author’s gravatar author

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:

Then place the next part inbetween line 9 & 10:

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.

Author’s gravatar

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

Reply
Author’s gravatar author

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.

Author’s gravatar

hello,

your script is amazing! thanks!

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

thanks in advance!

Reply
Author’s gravatar author

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:

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.

Author’s gravatar

Hello Paul,

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

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

can you help me?

thanks in advance!

Author’s gravatar author

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.

Author’s gravatar

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

You can tell me whats wrong with my code?

This generate a error.

Really thanks!

Author’s gravatar author

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:

Author’s gravatar

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.

Author’s gravatar author

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:

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

Author’s gravatar

it works!!!

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

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

Author’s gravatar author

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.

Author’s gravatar

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

Reply
Author’s gravatar author

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.

Author’s gravatar

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

Reply
Author’s gravatar author

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. 🙁

Author’s gravatar

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

Reply
Author’s gravatar author

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. 😉

Author’s gravatar

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:

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!

Reply
Author’s gravatar author

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:

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:

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. 😉

Author’s gravatar

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!

Reply
Author’s gravatar author

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.

Author’s gravatar

Thank you very much for your solution, this has helped me solve my problem! I was using get_posts function, which didn’t care about sort order and limited the contents of array to 4 images, instead of how many i had.

Again, appreciate your help! 🙂

Reply
Author’s gravatar

Thank you very much for this. I have a question though, how would you access the FIELDS that are available to each attachment (like the description as opposed to the title)? I didn’t see this in the get_children arguments…

Reply
Author’s gravatar author

Hi Marco,

Everything should be available under the $attachment variable. I can’t remember what the names are, but you can print_r($attachment); to see what the field names are.

Author’s gravatar

This is exactly what I’ve been digging all around the net. Totally worth the hours. 🙂

Reply
Author’s gravatar

This is so very, very close to what I want to achieve it’s just not quite working for me… I’d be incredibly grateful if you could help me with this!

It’s generating a list of images and the link through to the full size images is correct, the problem is the image url seems to be incorrect so the images aren’t displaying on the post.

It currently displays this:

What I want it to display is the URL to the medium sized image which should be this:

(note the .jpg is after the dimensions)

Any ideas? I think the problem is, my theme does not have a thumb.php file, instead WordPress generates a series of images on upload.

Reply
Author’s gravatar author

Hi Dan,

I’ve just realized that this post should be updated. WordPress now has a very easy way to do this using it’s built in media functions. The code in your case would look a little like this:

Something like that should have the desired result. WP has gained a fair amount of media functions since I wrote this tutorial (back in 2010). I’ll add a note at the top explaining that it is fairly old now.

Author’s gravatar

Hi
I am using following code to display images[url] attached to a particular single post but in my case it display all images[url] in media library rather than a images[url] attached to a single post. I have post with images attached to it through [gallery] shortcode and i want to display that images[url] only.

ID), array(130, 130), false, ”); ?>

$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);

?>
<a href="” data-rel=”prettyPhoto[mixed]” rel=”prettyPhoto[mixed]”>

<img alt="" src="”>

Reply
Author’s gravatar

hi
my problem solved..
i forgot to wrote global $post.

Reply
Author’s gravatar

I have a post that have 100+ image attachments. All image were renamed (before upload) to page-1.jpg, page-2.jpg and so on. So i want to display the whole list of images sorted by file name.

I’m using this code but the order is somehow… well, not in order 🙂

‘attachment’,
‘post_mime_type’ => ‘image’,
‘posts_per_page’ => -1,
‘post_parent’ => $post->ID,
‘order’ => ‘DESC’,
‘orderby’ => ‘menu_order ID’,
‘exclude’ => get_post_thumbnail_id()
) );

if ($attachments) {
foreach ($attachments as $attachment) {
$class = “post-attachment mime-” . sanitize_title( $attachment->post_mime_type );
$thumbimgL = wp_get_attachment_image_src( $attachment->ID, ‘magazine-full’ );
$thumbimgF = wp_get_attachment_image_src( $attachment->ID, ‘magazine-full’ );
echo ‘ ‘;
echo ‘ ‘;
echo ‘ ‘;
echo ”;
}
}
?>

Reply
Author’s gravatar author

Hi,

That would be because it is set to order by ‘menu_order ID’. That means order by the order shown in the gallery or, if one has not been set, order by the ID. The ID is, in most cases, the order which you uploaded them.

The only way I can think to order by the filename is to do it manually. Get WordPress to give you back your attachments, use the code:

Store them in an array then use a PHP array sorting function to sort them by the filename. Unfortunately I don’t have much time to go into much more detail than that, but hopefully it does help.

Author’s gravatar

Just making sure you were aware of the new function for this in 3.6.

Reply
Author’s gravatar author

Hi Randy,

I’d heard about that function, but I thought it had been removed when they did the 3.6 roll back of the post format UI. I’m glad they’d decided to keep it in the current core, will definitely come in handy.

Thanks for letting me know & I’ve updated the post to use that new piece of code. As always much appreciative of the feedback. 😉

Author’s gravatar

Thanks for showing how to create a Photo gallery for wordpress. This is a nice tutorial.

Reply
Older Comments
Newer Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more