I’m using the latest build of WP and would like to display the first image attached to the post at the top of the post content. What code do I have to add to single.php to make this happen?
Leave a Reply
You must be logged in to post a comment.
I’m using the latest build of WP and would like to display the first image attached to the post at the top of the post content. What code do I have to add to single.php to make this happen?
You must be logged in to post a comment.
Attachments are considered children of the post they’re attached to, so this should work:
for a large image… replace “large” with the size definition you want or a width,height array.
Function to get first image attached to a post
Now we need to tell WordPress where to display this image
Add this line where you want to display the image:
The Gotcha for using this aproach
If you add an image to the post editor it will display 2 times.
A case for using this approach
This works great when you want to use thumbnails(featured image) on your blog pages then display a larger version of the image in single.php and don’t want to have to set a featured image then manually insert it. With this method you just set the featured image to attach it to the post and be done with it.
I’m not sure how to limit it to the first attachment (and how to limit it to image attachments), but this should be a good starting point. From The Codex: