Using WordPress ‘attachment_link’ PHP filter

The attachment_link WordPress PHP filter modifies the permalink for an attachment.

Usage

add_filter('attachment_link', 'your_custom_function', 10, 2);

function your_custom_function($link, $post_id) {
    // Your custom code here
    return $link;
}

Parameters

  • $link (string) – The attachment’s permalink.
  • $post_id (int) – Attachment ID.

More information

See WordPress Developer Resources: attachment_link

Examples

Add a custom query parameter source with value gallery to the attachment link.

add_filter('attachment_link', 'add_custom_query_parameter', 10, 2);

function add_custom_query_parameter($link, $post_id) {
    // Add custom query parameter to the attachment link
    $link = add_query_arg('source', 'gallery', $link);
    return $link;
}

Append the attachment ID to the permalink with a hyphen.

add_filter('attachment_link', 'append_attachment_id', 10, 2);

function append_attachment_id($link, $post_id) {
    // Append attachment ID to the link
    $link = trailingslashit($link) . $post_id;
    return $link;
}

Replace the default attachment permalink with a custom structure: site_url/media/attachment-slug/

add_filter('attachment_link', 'custom_attachment_permalink', 10, 2);

function custom_attachment_permalink($link, $post_id) {
    $post = get_post($post_id);
    $custom_link = home_url('/media/' . $post->post_name . '/');
    return $custom_link;
}



Modify the attachment link based on the attachment's file type (e.g., image or video).


add_filter('attachment_link', 'modify_link_based_on_type', 10, 2);

function modify_link_based_on_type($link, $post_id) {
    // Get attachment file type
    $type = wp_check_filetype(get_attached_file($post_id));

    // Modify link for images
    if ($type['type'] === 'image/jpeg' || $type['type'] === 'image/png') {
        $link = add_query_arg('type', 'image', $link);
    }
    // Modify link for videos
    elseif ($type['type'] === 'video/mp4') {
        $link = add_query_arg('type', 'video', $link);
    }

    return $link;
}

Redirect attachment link to post parent


Redirect the attachment link to its parent post.


add_filter('attachment_link', 'redirect_to_parent_post', 10, 2);

function redirect_to_parent_post($link, $post_id) {
    // Get parent post of the attachment
    $parent_post = wp_get_post_parent_id($post_id);

    if ($parent_post) {
        // Redirect attachment link to parent post
        $link = get_permalink($parent_post);
    }

    return $link;
}