dan
dan

Reputation: 43

Wordpress Image Attachment with Link

Trying to replace the words "LINK TEXT HERE" with the attachment/image. How can I do this?

 <?php  
$args = array(
    'post_type' => 'attachment',
    'numberposts' => -1,
    'offset' => 0,
    'orderby' => 'menu_order',
    'order' => 'asc',
    'post_status' => null,
    'post_parent' => $post->ID,
    );
$attachments = get_posts($args);
if ($attachments) {
    foreach ($attachments as $attachment) {
        if(wp_attachment_is_image( $attachment->ID )) {
        echo '<a href="'. get_attachment_link($attachment->ID) . '">LINK TEXT HERE</a>';
        break;
    }
}
}

?>

Upvotes: 3

Views: 2811

Answers (3)

Tom Auger
Tom Auger

Reputation: 20101

wp_get_attachment_link( $attachment->ID );

This does it all in one, simple, compact WordPress API call. It wraps wp_get_attachment_image() in anchor tags, linking to the attachment.

Upvotes: 1

Glenn Slaven
Glenn Slaven

Reputation: 34193

echo '<a href="'. get_attachment_link($attachment->ID) . '">'. wp_get_attachment_image($attachment->ID) .'</a>';

Upvotes: 3

dan
dan

Reputation: 43

<?php  
        $args = array(
        'post_parent' => $post->ID,
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'orderby' => 'menu_order',
        'order' => 'ASC',
        'offset' => '1',
        'numberposts' => 1 
        );
        $attachments = get_posts($args);
        if ($attachments) {
        foreach ($attachments as $attachment) {
        if(wp_attachment_is_image( $attachment->ID )) {
        echo '<a href="'. wp_get_attachment_url($attachment->ID) . '" class="thumbnail">'. wp_get_attachment_image($attachment->ID) .'</a>';
        break;
        }
        } 
        }
    ?>

Thanks you Glen for providing the way to find the answer!

Upvotes: 1

Related Questions