WordPress How to get attachment file name by id

  • Post author:
  • Post category:Wordpress

To get the attachment file name by its ID in WordPress, you can use the wp_get_attachment_metadata() function to retrieve attachment metadata, which includes the file name. Here’s how you can do it:

$attachment_id = 123; // Replace 123 with the actual attachment ID you want to retrieve.

$attachment_metadata = wp_get_attachment_metadata($attachment_id);

if ($attachment_metadata) {
    $file_name = basename($attachment_metadata['file']);
    echo "File Name: " . $file_name;
} else {
    echo "Attachment not found or does not exist.";
}

In the code above:

  1. Replace 123 with the actual attachment ID you want to retrieve.
  2. We use wp_get_attachment_metadata() to fetch the metadata associated with the attachment ID. The metadata includes various details about the attachment, including the file path.
  3. We check if the $attachment_metadata variable contains data. If it does, we extract the file name using basename() from the file path stored in the metadata and then echo it.

This code will output the file name of the attachment associated with the specified ID.