Retrieve permalink for attachment.

This can be used in the WordPress Loop or outside of it.

Signature

get_attachment_link( $post = null, $leavename = false )
post
 (int|object) Optional. Post ID or object.
Default: null
leavename
 (boolean) Optional. Leave name.
Default: false

Return

(string)

Source

function get_attachment_link( $post = null, $leavename = false ) {
	global $wp_rewrite;

	$link = false;

	$post = get_post( $post );
	$parent = ( $post->post_parent > 0 && $post->post_parent != $post->ID ) ? get_post( $post->post_parent ) : false;

	if ( $wp_rewrite->using_permalinks() && $parent ) {
		if ( 'page' == $parent->post_type )
			$parentlink = _get_page_link( $post->post_parent ); // Ignores page_on_front
		else
			$parentlink = get_permalink( $post->post_parent );

		if ( is_numeric($post->post_name) || false !== strpos(get_option('permalink_structure'), '%category%') )
			$name = 'attachment/' . $post->post_name; // <permalink>/<int>/ is paged so we use the explicit attachment marker
		else
			$name = $post->post_name;

		if ( strpos($parentlink, '?') === false )
19 more lines...
WP Trac GitHub

Link here