get_attached_file()WP 2.0.0

Gets the absolute (server) path of the attachment (attached file) by the provided attachment ID.

The path is located in the meta-field of the attachment: _wp_attached_file. The function simply retrieves the value of this field and combines it with wp_upload_dir().

Use wp_get_attachment_url() to get the URL of the attachment file, not its path.

1 time — 0.000594 sec (slow) | 50000 times — 0.41 sec (very fast) | PHP 7.0.8, WP 4.6
Hooks from the function

Returns

String|false. The path to the attached file or false if the path could not be retrieved.

Usage

get_attached_file( $attachment_id, $unfiltered );
$attachment_id(number) (required)
ID of the attachment for which the path needs to be retrieved.
$unfiltered(boolean)
By default, the retrieved path is processed by the filter get_attached_file, but if true is specified for this parameter, the path will not be filtered.
Default: false

Examples

0

#1 Get the full path to the attachment file

$attach_id = 5;

$attached_path = get_attached_file( $attach_id );
//> /home/www/example.com/wp-content/uploads/2014/11/file_name.png

$filename = basename( $attached_path ); 
//> file_name.png

Changelog

Since 2.0.0 Introduced.

get_attached_file() code WP 6.8.1

function get_attached_file( $attachment_id, $unfiltered = false ) {
	$file = get_post_meta( $attachment_id, '_wp_attached_file', true );

	// If the file is relative, prepend upload dir.
	if ( $file && ! str_starts_with( $file, '/' ) && ! preg_match( '|^.:\\\|', $file ) ) {
		$uploads = wp_get_upload_dir();
		if ( false === $uploads['error'] ) {
			$file = $uploads['basedir'] . "/$file";
		}
	}

	if ( $unfiltered ) {
		return $file;
	}

	/**
	 * Filters the attached file based on the given ID.
	 *
	 * @since 2.1.0
	 *
	 * @param string|false $file          The file path to where the attached file should be, false otherwise.
	 * @param int          $attachment_id Attachment ID.
	 */
	return apply_filters( 'get_attached_file', $file, $attachment_id );
}