Using WordPress ‘get_attached_file’ PHP filter

The get_attached_file WordPress PHP filter retrieves the file path of an attached file using the given attachment ID.

Usage

add_filter('get_attached_file', 'your_custom_function', 10, 2);

function your_custom_function($file, $attachment_id) {
    // your custom code here
    return $file;
}

Parameters

  • $file (string|false): The file path to where the attached file should be, or false if not found.
  • $attachment_id (int): The attachment ID.

More information

See WordPress Developer Resources: get_attached_file

Examples

Change the file path for specific attachments

Modify the file path for attachments with specific IDs.

add_filter('get_attached_file', 'change_specific_file_path', 10, 2);

function change_specific_file_path($file, $attachment_id) {
    if ($attachment_id == 123 || $attachment_id == 456) {
        $file = '/new/path/to/your/file.jpg';
    }
    return $file;
}

Replace file extensions

Replace the file extension of all attachments with a custom one.

add_filter('get_attached_file', 'replace_file_extension', 10, 2);

function replace_file_extension($file, $attachment_id) {
    $file = preg_replace('/\.(.+)$/', '.custom-extension', $file);
    return $file;
}

Add a version number to file paths

Append a version number to the file paths of all attachments.

add_filter('get_attached_file', 'add_version_number', 10, 2);

function add_version_number($file, $attachment_id) {
    $file = $file . '?ver=1.0';
    return $file;
}

Change the base directory of attachment files

Move attachment files to a custom directory.

add_filter('get_attached_file', 'change_base_directory', 10, 2);

function change_base_directory($file, $attachment_id) {
    $file = str_replace('/wp-content/uploads/', '/custom/uploads/directory/', $file);
    return $file;
}

Prevent access to specific file types

Restrict access to certain file types by returning false for their paths.

add_filter('get_attached_file', 'prevent_specific_file_types', 10, 2);

function prevent_specific_file_types($file, $attachment_id) {
    if (preg_match('/\.(exe|bat|sh)$/i', $file)) {
        return false;
    }
    return $file;
}