get_attached_file() WordPress Function

The get_attached_file() function is used to retrieve the full path to an attached file. This function can be used with any post type, but is most commonly used with the 'attachment' post type.

get_attached_file( int $attachment_id, bool $unfiltered = false ) #

Retrieve attached file path based on attachment ID.


Description

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.


Top ↑

Parameters

$attachment_id

(int)(Required)Attachment ID.

$unfiltered

(bool)(Optional) Whether to apply filters.

Default value: false


Top ↑

Return

(string|false) The file path to where the attached file should be, false otherwise.


Top ↑

Source

File: wp-includes/post.php

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 && 0 !== strpos( $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 );
}


Top ↑

Changelog

Changelog
VersionDescription
2.0.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More