Using WordPress ‘get_ancestors’ PHP filter

The get_attached_file WordPress PHP filter allows you to modify the file path of an attached file based on its 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 no file is found.
  • $attachment_id (int) – The ID of the attachment.

More information

See WordPress Developer Resources: get_attached_file

Examples

Change Attachment File Path

Modify the file path of an attachment to a custom directory.

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

function change_attachment_file_path( $file, $attachment_id ) {
    // Replace 'your-custom-directory' with your desired directory
    $custom_path = 'your-custom-directory/' . basename( $file );
    return $custom_path;
}

Check Attachment File Size

Retrieve the file size of an attachment before performing an action.

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

function check_attachment_file_size( $file, $attachment_id ) {
    $file_size = filesize( $file );

    if ( $file_size < 1000000 ) { // 1MB
        // Perform your desired action
    }

    return $file;
}

Change Attachment File Extension

Modify the file extension of an attachment.

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

function change_attachment_file_extension( $file, $attachment_id ) {
    // Replace 'new-extension' with your desired file extension
    $new_extension = 'new-extension';
    $file_info = pathinfo( $file );
    $new_file = $file_info['dirname'] . '/' . $file_info['filename'] . '.' . $new_extension;
    return $new_file;
}

Add Timestamp to Attachment File Name

Append a timestamp to the file name of an attachment.

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

function add_timestamp_to_attachment_name( $file, $attachment_id ) {
    $file_info = pathinfo( $file );
    $timestamp = time();
    $new_file = $file_info['dirname'] . '/' . $file_info['filename'] . '_' . $timestamp . '.' . $file_info['extension'];
    return $new_file;
}

Apply Custom Function to Specific Attachment Type

Apply a custom function only to a specific attachment type, such as images.

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

function apply_custom_function_to_image_attachments( $file, $attachment_id ) {
    $mime_type = get_post_mime_type( $attachment_id );

    if ( wp_attachment_is_image( $attachment_id ) || strpos( $mime_type, 'image' ) !== false ) {
        // Apply your custom function here
    }

    return $file;
}