Forums

Display thumbnail of first attachment (5 posts)

  1. chriskjennings
    Member
    Posted 3 years ago #

    I found this function in wp-includes/media.php:

    // as per wp_get_attachment_image_src, but returns an <img> tag
    function wp_get_attachment_image($attachment_id, $size='thumbnail', $icon = false)

    I want to be able to display the thumbnail of the first post attachment in my loop, can I accomplish using this function?

    Is there a better way?

  2. disbas
    Member
    Posted 3 years ago #

    Justin Tadlock's Get-the-Image-plugin. Works like a charm.

  3. Otto
    Tech Ninja
    Posted 3 years ago #

    First, get the image attachments of the post:

    global $post;
    $attachments = get_children( array(
    'post_parent' => $post->ID,
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'orderby' => 'menu_order ASC, ID',
    'order' => 'DESC') );

    Next, go through them:

    foreach ( $attachments as $id => $attachment ) {
    // do whatever you want here with the $id being the $attachment_id
    }

    Like that.

  4. Dunkkan
    Member
    Posted 3 years ago #

    Hello, I'm trying to do exactly that but, which could be an example of the use of the $attachment_id ? Just for print the thumbnail i.e. ?

  5. cheese apples
    Member
    Posted 3 years ago #

    I enjoy this plugin. It also has some great options in the settings.

    http://wordpress.org/extend/plugins/alakhnors-post-thumb/

    Upload/activate the plugin, then use <?php the_thumb(); ?> inside the loop to display the first image added to your posts/pages.

    If you are using the_content in this loop, and inserted your first uploaded image within the post. You can use preg_replace as shown below to strip the img tags from the_content. This way to can display your thumbnails as above however you want and have text only in the_content. Replace your the_content line with below to do so.

    <?php
    ob_start();
    the_content('Read the full post',true);
    $postOutput = preg_replace('/<img[^>]+./','', ob_get_contents());
    ob_end_clean();
    echo $postOutput;
    ?>

    Using both examples, you can do some nifty stuff for example float left on the thumbnail, to text wrap the post title, etc as well as the content.

Topic Closed

This topic has been closed to new replies.

About this Topic