WordPress get_attachment_link() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Returns a URL

Definition

In WordPress, get_attachment_link() returns the URL of an attachment page. An attachment is a file you upload to the Media Library, such as an image or a PDF.

Do not mix it up with the file URL. The attachment link opens a WordPress page about the file. The file URL, from wp_get_attachment_url(), opens the file itself.

Syntax

Pass the attachment ID, or call it inside an attachment template.

WordPress
<?php echo esc_url( get_attachment_link( 57 ) ); ?>
CallWhat it does
get_attachment_link( 57 )The page URL of attachment 57.
get_attachment_link()The page URL of the current attachment.
get_attachment_link( 57, true )Keep the name part as a placeholder.

It returns the link. Print it with esc_url().

Full declaration
WordPress
get_attachment_link( int|WP_Post $post = null, bool $leavename = false ): string

Parameters

ParameterDescription
$postint|WP_Post. The attachment ID or object. Default is null, which means the current post.
$leavenamebool. If true, the name part of the URL stays as a placeholder such as %postname%. Default is false.

Return Value

Return ValueDescription
stringThe URL of the attachment page.

WordPress Examples

Three short examples. Each one shows the code and what it prints or does.

Example 1 — Get an attachment page URL

Pass the ID of an uploaded image.

WordPress
<?php
echo esc_url( get_attachment_link( 57 ) );

How It Works

  1. 57 is the Media Library ID.
  2. WordPress builds the attachment page address.
  3. The path often includes the parent post name.

Example 3 — Use it in an attachment template

In image.php or attachment.php, no ID is needed.

WordPress
<?php
// image.php
echo '<p>Permalink: ' . esc_url( get_attachment_link() ) . '</p>';

How It Works

  1. On an attachment page, the current post is the attachment.
  2. So get_attachment_link() needs no argument.
  3. esc_url() keeps the output safe.

Frequently Asked Questions

It returns the URL of the WordPress page for an uploaded file or image.
get_attachment_link() gives the attachment page. wp_get_attachment_url() gives the direct URL of the file.
No. It returns a string. Print it with echo and esc_url().
It uses the current post. That works inside an attachment template.
It keeps the name part of the URL as a placeholder. It is rarely needed in a theme.

Next: get_delete_post_link()

Return the URL that moves a post to the Trash, or deletes it for good.

get_delete_post_link() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful