Displaying Post Attachment(s) at Top of single.php

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?

Related posts

Leave a Reply

3 comments

  1. Attachments are considered children of the post they’re attached to, so this should work:

    $images=get_children( array('post_parent'=>$post->ID,
                                'post_mime_type'=>'image',
                                 'numberposts'=>1));
    echo wp_get_attachment_image($images[0]->ID, 'large');
    

    for a large image… replace “large” with the size definition you want or a width,height array.

  2. Function to get first image attached to a post

    function the_image($size = 'medium' , $class = ”){
    global $post;
    
    //setup the attachment array
    $att_array = array(
    'post_parent' => $post->ID,
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'order_by' => 'menu_order'
    );
    
    //get the post attachments
    $attachments = get_children($att_array);
    
    //make sure there are attachments
    if (is_array($attachments)){
    //loop through them
    foreach($attachments as $att){
    //find the one we want based on its characteristics
    if ( $att->menu_order == 0){
    $image_src_array = wp_get_attachment_image_src($att->ID, $size);
    
    //get url – 1 and 2 are the x and y dimensions
    $url = $image_src_array[0];
    $caption = $att->post_excerpt;
    $image_html = '<img src="%s" alt="%s" />';
    
    //combine the data
    $html = sprintf($image_html,$url,$caption,$class);
    
    //echo the result
    echo $html;
    }
    }
    }
    }
    

    Now we need to tell WordPress where to display this image

    Add this line where you want to display the image:

    <?php the_image('medium','post-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.

  3. 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:

    <?php
    
    $args = array(
        'post_type' => 'attachment',
        'numberposts' => -1,
        'post_status' => null,
        'post_parent' => $post->ID
        ); 
    $attachments = get_posts($args);
    if ($attachments) {
        foreach ($attachments as $attachment) {
            echo apply_filters('the_title', $attachment->post_title);
            the_attachment_link($attachment->ID, false);
        }
    }
    
    ?>