Using WordPress ‘get_attached_file()’ PHP function

The get_attached_file() WordPress PHP function retrieves the attached file path based on the attachment ID.


$attached_file_path = get_attached_file($attachment_id, $unfiltered);


  • $attachment_id (int) – The attachment ID for which the file path is to be retrieved.
  • $unfiltered (bool) – Optional. Whether to skip the ‘get_attached_file’ filter. Default is false.

More information

See WordPress Developer Resources: get_attached_file()


Retrieve full file path

Retrieve the full file path of an attachment.

$attachment_id = 123;
$full_file_path = get_attached_file($attachment_id);

Retrieve filename only

Retrieve only the filename of an attachment.

$attachment_id = 123;
$filename_only = basename(get_attached_file($attachment_id));

Retrieve unfiltered file path

Retrieve the unfiltered file path of an attachment, bypassing the ‘get_attached_file’ filter.

$attachment_id = 123;
$unfiltered_file_path = get_attached_file($attachment_id, true);

Display attachment file URL

Display the URL of an attachment file using wp_get_attachment_url().

$attachment_id = 123;
$attachment_url = wp_get_attachment_url($attachment_id);
echo $attachment_url;

Check if attachment is an image

Check if the attachment is an image by verifying its MIME type.

$attachment_id = 123;
$mime_type = get_post_mime_type($attachment_id);
if (strpos($mime_type, 'image/') === 0) {
    echo "The attachment is an image.";
} else {
    echo "The attachment is not an image.";