wp_get_attachment_url

Retrieve the URL for an attachment.

Description

(string|false) wp_get_attachment_url( (int) $post_id = 0 ); 

Returns (string|false)

Attachment URL, otherwise false.

Parameters (1)

0. $post_id — Optional. (int)
Attachment ID. Default 0.

Usage

  1. if ( !function_exists( 'wp_get_attachment_url' ) ) { 
  2. require_once ABSPATH . WPINC . '/post.php'; 
  3.  
  4. // Optional. Attachment ID. Default 0. 
  5. $post_id = -1; 
  6.  
  7. // NOTICE! Understand what this does before running. 
  8. $result = wp_get_attachment_url($post_id); 
  9.  

Defined (1)

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

/wp-includes/post.php  
  1. function wp_get_attachment_url( $post_id = 0 ) { 
  2. $post_id = (int) $post_id; 
  3. if ( !$post = get_post( $post_id ) ) 
  4. return false; 
  5.  
  6. if ( 'attachment' != $post->post_type ) 
  7. return false; 
  8.  
  9. $url = ''; 
  10. // Get attached file. 
  11. if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true ) ) { 
  12. // Get upload directory. 
  13. if ( ( $uploads = wp_get_upload_dir() ) && false === $uploads[error] ) { 
  14. // Check that the upload base exists in the file location. 
  15. if ( 0 === strpos( $file, $uploads['basedir'] ) ) { 
  16. // Replace file location with url location. 
  17. $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); 
  18. } elseif ( false !== strpos($file, 'wp-content/uploads') ) { 
  19. // Get the directory name relative to the basedir (back compat for pre-2.7 uploads) 
  20. $url = trailingslashit( $uploads['baseurl'] . '/' . _wp_get_attachment_relative_path( $file ) ) . basename( $file ); 
  21. } else { 
  22. // It's a newly-uploaded file, therefore $file is relative to the basedir. 
  23. $url = $uploads['baseurl'] . "/$file"; 
  24.  
  25. /** 
  26. * If any of the above options failed, Fallback on the GUID as used pre-2.7,  
  27. * not recommended to rely upon this. 
  28. */ 
  29. if ( empty($url) ) { 
  30. $url = get_the_guid( $post->ID ); 
  31.  
  32. // On SSL front end, URLs should be HTTPS. 
  33. if ( is_ssl() && ! is_admin() && 'wp-login.php' !== $GLOBALS['pagenow'] ) { 
  34. $url = set_url_scheme( $url ); 
  35.  
  36. /** 
  37. * Filters the attachment URL. 
  38. * @since 2.1.0 
  39. * @param string $url URL for the given attachment. 
  40. * @param int $post_id Attachment ID. 
  41. */ 
  42. $url = apply_filters( 'wp_get_attachment_url', $url, $post->ID ); 
  43.  
  44. if ( empty( $url ) ) 
  45. return false; 
  46.  
  47. return $url;