Skip to Content
28 January, 2023

How to replace media files without changing the URL in WordPress

Table of Content

Here’s an example of a function that you can use to replace media files in WordPress without changing the URL:


function replace_media_file($attachment_id, $new_file) {
// Get the path to the current file
$current_file = get_attached_file($attachment_id);
// Delete the current file
unlink($current_file);

// Copy the new file to the attachment's upload directory
copy($new_file, $current_file);

// Update the attachment's metadata
$attach_data = wp_generate_attachment_metadata($attachment_id, $current_file);
wp_update_attachment_metadata($attachment_id, $attach_data);

}
This function takes two parameters: the attachment ID of the media file you want to replace, and the path to the new file. It first gets the path to the current file using the get_attached_file() function, then deletes the current file using the unlink() function. It then copies the new file to the attachment’s upload directory using the copy() function. Finally, it updates the attachment’s metadata using the wp_update_attachment_metadata() function.

You can use this function by calling it and passing the attachment ID and new file path as arguments, for example:


replace_media_file(5, '/path/to/new-file.jpg');

It’s important to note that this function doesn’t handle error checking, validation, or image size check, so it’s recommended to add error checking and validation before using it in production.
Also, it’s important to make sure you have the right permissions to delete, copy, and update the files.

Insights

The latest from our knowledge base