get_attachment_link

Retrieves the permalink for an attachment.

Description

(string) get_attachment_link( (constant) $post = null, (bool) $leavename = false ); 

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

Returns (string)

The attachment permalink.

Parameters (2)

0. $post — Optional. (constant) => null
Post ID or object. Default uses the global $post..
1. $leavename — Optional. (bool) => false
Whether to keep the page name. Default false.

Usage

  1. if ( !function_exists( 'get_attachment_link' ) ) { 
  2. require_once ABSPATH . WPINC . '/link-template.php'; 
  3.  
  4. // Optional. Post ID or object. Default uses the global `$post`. 
  5. $post = null; 
  6.  
  7. // Optional. Whether to keep the page name. Default false. 
  8. $leavename = false; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = get_attachment_link($post, $leavename); 
  12.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/link-template.php  
  1. function get_attachment_link( $post = null, $leavename = false ) { 
  2. global $wp_rewrite; 
  3.  
  4. $link = false; 
  5.  
  6. $post = get_post( $post ); 
  7. $parent = ( $post->post_parent > 0 && $post->post_parent != $post->ID ) ? get_post( $post->post_parent ) : false; 
  8. if ( $parent && ! in_array( $parent->post_type, get_post_types() ) ) { 
  9. $parent = false; 
  10.  
  11. if ( $wp_rewrite->using_permalinks() && $parent ) { 
  12. if ( 'page' == $parent->post_type ) 
  13. $parentlink = _get_page_link( $post->post_parent ); // Ignores page_on_front 
  14. else 
  15. $parentlink = get_permalink( $post->post_parent ); 
  16.  
  17. if ( is_numeric($post->post_name) || false !== strpos(get_option('permalink_structure'), '%category%') ) 
  18. $name = 'attachment/' . $post->post_name; // <permalink>/<int>/ is paged so we use the explicit attachment marker 
  19. else 
  20. $name = $post->post_name; 
  21.  
  22. if ( strpos($parentlink, '?') === false ) 
  23. $link = user_trailingslashit( trailingslashit($parentlink) . '%postname%' ); 
  24.  
  25. if ( ! $leavename ) 
  26. $link = str_replace( '%postname%', $name, $link ); 
  27. } elseif ( $wp_rewrite->using_permalinks() && ! $leavename ) { 
  28. $link = home_url( user_trailingslashit( $post->post_name ) ); 
  29.  
  30. if ( ! $link ) 
  31. $link = home_url( '/?attachment_id=' . $post->ID ); 
  32.  
  33. /** 
  34. * Filters the permalink for an attachment. 
  35. * @since 2.0.0 
  36. * @param string $link The attachment's permalink. 
  37. * @param int $post_id Attachment ID. 
  38. */ 
  39. return apply_filters( 'attachment_link', $link, $post->ID );