Get Images Attached to a Post
Ever wonder how to pull the images attached to a WordPress post, to display as thumbnails on your homepage for instance? Here's a fairly simple way to get it done.
Ever wonder how to pull the images attached to a WordPress post, to display as thumbnails on your homepage for instance? Here's a fairly simple way to get it done.
When you upload an image (or other media file) through the Write Post or Write Page panel, WordPress remembers which post that file is attached to. This is a great feature if you want to pull some of the attached images for use as thumbnails on your blog's homepage for instance – similar to the way the Tutorials and Blog indexes are set up on this site.
For my project, I needed to get the attached images for a page outside of The Loop, so in this tutorial I'll show you both ways. First inside the loop, then I'll show you the changes to make to get this done outside the loop.
Also, I'm trying a new strategy this time around… Instead of giving you the complete code and then going through each section step by step, I'm shortening this post a bit by only showing the complete code…but well-commented so you can see what's going on. Let me know what you think about this strategy and if you'd prefer to see the step by step break down like I've done in previous tutorials.
One thing to keep in mind is that inside the loop, the $post object is set, and so we can access its various properties using the $post->;PROPERTY syntax. So we first need to create a new function in our functions.php file.
Next you just need to call the function from wherever you want the image to show up at.
The main difference to get this done outside the loop is that the $post object won't be set (or rather it will be set, but can't be used reliably), so we need to either know the post ID we want the images for, or we need to be on the post/page that we want the images for, but just outside of the loop for that post/page.
If we're on the post/page but outside the loop (i.e. in the sidebar), we can use the get_the_ID() function to get the ID of the current post/page. So instead of $iPostID = $post->;ID, we could use $iPostID = get_the_ID().
If we want to pull the images from a post/page other than the one we're currently viewing, we'd have to pass the post ID of the post/page we want to the bdw_get_images() function as a parameter when calling the function.