I'm looking to find a solution that enables me to get the ID of the first image attached to a post in the loop.

I'm currently using this;

$size = 'post-thumbnail'; // Define image_size to be used
$args = array(
    'post_type'        => 'attachment',
    'post_mime_type'   => 'image',
    'post_parent'      => $post->ID
$images = get_posts($args);
$attachment_id = $images[0]->ID;
$i = wp_get_attachment_image_src($attachment_id, $size);

if (has_post_thumbnail()) { // Check if post thumbnail is present first
} else { // If no post thumbnail is present, echo first image in post
    echo '<img src="'.$i[0].'" alt=""/>';

Which works fine if it's on a single post, but doesn't work correctly in a loop of posts (It only gets the ID on 1 post as oppose to all of them).

I've googled around and every function I've found seems to have the same issue, it only gets the ID for one post.

Can anyone help me out?

This needs to be a function and NOT a plugin.

  • Is there any particular reason it can't be a plugin? ( having 1000 small plugins can be faster than a single humonguous plugin or a giant theme functions.php ). Also to be clear you mean images attached to a post or images attached to a post that also appear in the content? The two are very different things. – Tom J Nowell May 7 '14 at 10:34
  • Can you let me know what the results of using this loop with extra added debugging information are? gist.github.com/Tarendai/8688f6dc45e215b37b91 – Tom J Nowell May 7 '14 at 10:43

I assume all your code is wrapped inside the loop? And you should check that a post does indeed have attachments before operating on the $images array:

while ( have_posts() ) {

    if ( has_post_thumbnail() ) {
        the_post_thumbnail( /* No need for "post-thumbnail" argument, it's the default. */ ); 
    } else {
        // No post thumbnail, try attachments instead.
        $images = get_posts(
                'post_type'      => 'attachment',
                'post_mime_type' => 'image',
                'post_parent'    => $post->ID,
                'posts_per_page' => 1, /* Save memory, only need one */

        if ( $images ) {
            echo '<img src="' . wp_get_attachment_image_src( $images[0]->ID, 'post-thumbnail' ) . '" alt="" />';

Note that I've re-structured your code a little - there's no need to burden the server and query for attachments if the post already has a thumbnail.

  • Would this catch images that aren't uploaded to the post itself as well? Say an image is used that has already been uploaded to another post, wouldn't the older post be it's parent? – Emil Jan 11 '16 at 13:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.