get_attached_file

Retrieve attached file path based on attachment ID.

Description

(string|false) get_attached_file( (int) $attachment_id, (bool) $unfiltered = false ); 

By default the path will go through the get_attached_file filter, but passing a true to the $unfiltered argument of get_attached_file() will return the file path unfiltered.

The function works by getting the single post meta name, named '_wp_attached_file' and returning it. This is a convenience function to prevent looking up the meta name and provide a mechanism for sending the attached filename through a filter.

Returns (string|false)

The file path to where the attached file should be, false otherwise.

Parameters (2)

0. $attachment_id (int)
The attachment id.
1. $unfiltered — Optional. (bool) => false
Whether to apply filters. Default false.

Usage

  1. if ( !function_exists( 'get_attached_file' ) ) { 
  2. require_once ABSPATH . WPINC . '/post.php'; 
  3.  
  4. // The attachment id. 
  5. $attachment_id = -1; 
  6.  
  7. // Optional. Whether to apply filters. Default false. 
  8. $unfiltered = false; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = get_attached_file($attachment_id, $unfiltered); 
  12.  

Defined (1)

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

/wp-includes/post.php  
  1. function get_attached_file( $attachment_id, $unfiltered = false ) { 
  2. $file = get_post_meta( $attachment_id, '_wp_attached_file', true ); 
  3.  
  4. // If the file is relative, prepend upload dir. 
  5. if ( $file && 0 !== strpos( $file, '/' ) && ! preg_match( '|^.:\\\|', $file ) && ( ( $uploads = wp_get_upload_dir() ) && false === $uploads[error] ) ) { 
  6. $file = $uploads['basedir'] . "/$file"; 
  7.  
  8. if ( $unfiltered ) { 
  9. return $file; 
  10.  
  11. /** 
  12. * Filters the attached file based on the given ID. 
  13. * @since 2.1.0 
  14. * @param string $file Path to attached file. 
  15. * @param int $attachment_id Attachment ID. 
  16. */ 
  17. return apply_filters( 'get_attached_file', $file, $attachment_id );