WordPress.org

Ready to get started?Download WordPress

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/get attachment link

Contents

Description

Returns the URI of the page for an attachment.

Usage

 <?php $attachment_page get_attachment_link($id); ?> 

Parameters

$id
(integer) (optional) The numeric ID of the attachment.
Default: The current post ID, when used in The Loop.

Examples

Default Usage

As the tag does not display the permalink, the example uses the PHP echo command.

<?php 
$attachment_id = 1; // ID of attachment
$attachment_page = get_attachment_link( $attachment_id ); 
?>
<a href="<?php echo $attachment_page; ?>"><?php echo get_the_title( $attachment_id ); ?></a>

Display attached images and titles as a list

To display the images attached to a certain page and display them as a list of bullets you can use the following:

<ul>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();    

 $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 '<li>';
           the_attachment_link( $attachment->ID, true );
           echo '<p>';
           echo apply_filters( 'the_title', $attachment->post_title );
           echo '</p></li>';
          }
     }

 endwhile; endif; ?>
</ul>

Return value

Under a "pretty" permalink structure, the function returns something like http://wp.example.net/path_to_post/post_name/attachment_name.

Under the default permalink structure — or if Wordpress can't construct a pretty URI — the function returns something like http://wp.example.net/?attachment_id=n, where n is the attachment ID number.

Notes

You can change the output of this function through the attachment_link filter.

If you want a direct link to the attached file (instead of the attachment page), you can use the function wp_get_attachment_url(id) instead.

Note: that get_attachment_link actually returns an URI, whereas wp_get_attachment_link() returns an HTML hyperlink.

Source File

get_attachment_link() is located in wp-includes/link-template.php.

Related

Attachment Functions:

get_children(), get attached media(), the_attachment_link(), get_attachment_link(), wp_get_attachment_link(), wp_get_attachment_image(), wp_get_attachment_image_src(), wp_get_attachment_url(), wp_get_attachment_thumb_file(), wp_get_attachment_thumb_url(), is_attachment(), wp_get_attachment_metadata()