Using WordPress ‘get_attachment_link()’ PHP function

The get_attachment_link() WordPress PHP function retrieves the permalink for an attachment.

Usage

get_attachment_link($post, $leavename)

Input:

  • $post: The ID of an attachment or the attachment object.
  • $leavename: A boolean value to indicate whether to keep the page name.

Output:

  • Returns the permalink URL for the specified attachment.

Parameters

  • $post (int|object) – Optional. Post ID or object. Default uses the global $post. Default: null
  • $leavename (bool) – Optional. Whether to keep the page name. Default: false

More information

See WordPress Developer Resources: get_attachment_link()

Examples

This code snippet displays the attachment link for a specific attachment ID:

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

Displaying attached images and titles as a list

This code snippet displays all attached images and titles as a list of bullets:

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) {
            echo '<ul>';
            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>';
            }
            echo '</ul>';
        }
    endwhile;
endif;

Displaying attached files to a specific post

This code snippet displays all attached files to a specific post ID:

$post_id = 42;
$args = array(
    'post_type' => 'attachment',
    'post_parent' => $post_id,
    'post_mime_type' => 'application/pdf',
);
$attachments = get_posts($args);
if ($attachments) {
    echo '<ul>';
    foreach ($attachments as $attachment) {
        $attachment_link = get_attachment_link($attachment->ID);
        echo '<li><a href="' . esc_url($attachment_link) . '">' . get_the_title($attachment->ID) . '</a></li>';
    }
    echo '</ul>';
}

Displaying attached image with a custom size

This code snippet displays an attached image with a custom size:

$attachment_id = 1;
$attachment_link = get_attachment_link($attachment_id);
$image_src = wp_get_attachment_image_src($attachment_id, 'custom-size');
<a href="<?php echo esc_url($attachment_link); ?>"><img src="<?php echo esc_url($image_src[0]); ?>" alt="<?php echo get_the_title($attachment_id); ?>"></a>