Making images from single.php pointing to an attachment .php template

If I understand you correctly, you need to link your images not to the file, but to the attachment template (attachment.php). If so, then try the following code in your single.php:

 <?php if( has_post_thumbnail() ) {
    $attachment_page_url="";
    $attachment_page_url = get_attachment_link( get_post_thumbnail_id() ); ?>
    <a href="<?php echo $attachment_page_url; ?>" class="featured-image">
        <?php the_post_thumbnail(); ?>
    </a>
<?php } ?>

We are checking if there’s any post_thumbnail (Featured Image), then if found getting the attachment link using the post_thumbnail_id, and passing that to the anchor tag of the featured image.

Hope that’s clear. 🙂

EDIT

So you’re affirmative that the bit of code you mentioned actually works, but it’s fetching only one image (the last one only). So, I’m sticking with the same code with slight changes:

<?php
$attachments = get_children( array(
                        'post_type' => 'attachment',
                        'post_mime_type'=>'image',
                        'numberposts' => -1,
                        'post_status' => 'inherit',
                        'post_parent' => $post->ID
                    )
                );
if( $attachments ) {
   foreach ( $attachments as $attachment ) {
       echo wp_get_attachment_link( $attachment->ID, '' , TRUE, FALSE, 'Link to image attachment' );
   }
} else {
   echo ''; //if no attachment found
}

Please note that I’ve changed in 4 positions:

  1. Removed the first if() condition and put it below
  2. Made the 'numberposts' to ‘all’ using a -1
  3. Changed the ‘post_status’ to 'inherit', as attachments are in that status
  4. And most importantly in your case, changed the number of posts (in posts_per_page) to 5, because you need 5 images.

But the code will fetch only 5 image-link, though there can be a lot. And you are actually getting showing 5 links only.

EDIT #2

You are missing a basic thing. When inserting an image into a post content, where you want to let the user go is up to you, because you have the control there.
Image insertion in Content area targeting attachment template

No need to do any query or linking. It’s that simple. 🙂

Leave a Comment