• Hey guys,
    I’m using the following code to get the image attachment for each post and display them. That part works fine but now I’m trying to link the image attachment to the post. I’m using the following code:

    <?php
    $args = array(
    'post_type'   => 'attachment',
    'numberposts' => -1,
    'post_status' => null,
    'post_parent' => $post->ID,
    'exclude'     => get_post_thumbnail_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, false, true );
    }
    }
    ?>

    It seems to get the permalink but then adds the filename of the attachment afterwards.
    For example, say if I had a post called “hello there” with the permalink “hello-there” and it included an image attachment called goodbye.jpg. The code above displays displays the attachment but links it to https://www.website.com/hello-there/goodbye
    Hope that makes sense? I have no idea why it’s sticking the attatchment name on the end. Without that it would work fine.
    Any help is appreciated.
    Thanks

  • The topic ‘Link the attatchment to post’ is closed to new replies.