Introduction
If you’ve ever needed to update a file in WordPress—like a PDF or an image—you’ve probably run into the issue where WordPress changes the file’s URL after it’s been replaced. This can be particularly frustrating if the file is linked across multiple pages on your site, as it requires you to manually update each link.
By default, WordPress does not offer an option to replace an existing media file. When you upload a new file with the same name as an existing one, WordPress creates a new file with a modified name (usually appending -1
, -2
, etc., to the filename) and stores it in the uploads directory for the current month. This behavior preserves old files but isn’t ideal if you want to simply update a file and keep all existing links intact.
In this tutorial, I’ll walk you through how to create a custom WordPress plugin that allows you to replace media files without changing their URL. This is a handy tool if you need to update files frequently and want to avoid the hassle of broken links or outdated content.
The Problem: Changing URLs When Replacing Files
As mentioned earlier, WordPress’s default behavior is to avoid overwriting files with the same name. If you upload a file with the same name as an existing one, WordPress will automatically append -1
, -2
, etc., to the filename and store it in the uploads directory for the current year and month. This ensures that existing files are preserved, but it also means that any links pointing to the original file will now be broken unless manually updated.
This behavior is great for preserving old versions of files, but it’s not ideal if you want to replace a file and keep the existing URL intact. Fortunately, with a bit of custom code, you can modify this behavior to suit your needs.
Creating the Media File Replacer Plugin
Let’s build a custom WordPress plugin that allows you to replace a file in the media library without changing its URL. This plugin will let you upload a new file, overwrite the existing file, and keep the original URL.
Step 1: Setting Up the Plugin
First, create a new folder named media-replacer
in your wp-content/plugins
directory. Inside this folder, create a file named media-replacer.php
and add the following code:
<?php
/*
Plugin Name: Media File Replacer
Description: Allows admin users to replace media files (e.g., PDFs) without changing the URL.
Version: 1.3
Author: Your Name
*/
// Function to add the "Replace File" link in the media library
function media_replacer_add_replace_link($actions, $post) {
if ($post->post_mime_type == 'application/pdf') {
$actions['replace_file'] = '<a href="' . admin_url('upload.php?page=replace-media&attachment_id=' . $post->ID) . '">Replace File</a>';
}
return $actions;
}
add_filter('media_row_actions', 'media_replacer_add_replace_link', 10, 2);
// Function to handle the file replacement page
function media_replacer_replace_file_page() {
// Check if the user has the right capability
if (!current_user_can('upload_files')) {
wp_die(__('Sorry, you are not allowed to access this page.'));
}
if (isset($_GET['page']) && $_GET['page'] == 'replace-media' && isset($_GET['attachment_id'])) {
$attachment_id = intval($_GET['attachment_id']);
$attachment = get_post($attachment_id);
if ($attachment && $attachment->post_mime_type == 'application/pdf') {
if (isset($_FILES['new_file'])) {
$new_file = $_FILES['new_file'];
// Check if the upload has any errors
if ($new_file['error'] == UPLOAD_ERR_OK) {
// Get the current file path
$old_file_path = get_attached_file($attachment_id);
$original_dir = pathinfo($old_file_path, PATHINFO_DIRNAME);
$original_filename = pathinfo($old_file_path, PATHINFO_BASENAME);
$new_file_path = $original_dir . '/' . $original_filename;
// Move the uploaded file to the original directory and overwrite the old file
if (move_uploaded_file($new_file['tmp_name'], $new_file_path)) {
// Update the attachment file path
update_attached_file($attachment_id, $new_file_path);
// Update the attachment metadata (like file size, etc.)
wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $new_file_path));
echo '<div class="notice notice-success"><p>File replaced successfully.</p></div>';
} else {
echo '<div class="notice notice-error"><p>Error: The uploaded file could not be moved to the original directory.</p></div>';
}
} else {
echo '<div class="notice notice-error"><p>File upload error. Please try again.</p></div>';
}
}
// Display the upload form
echo '<h2>Replace File</h2>';
echo '<form method="post" enctype="multipart/form-data">';
echo '<input type="file" name="new_file" accept="application/pdf" required />';
echo '<br><br>';
echo '<input type="submit" class="button button-primary" value="Replace File" />';
echo '</form>';
}
}
}
// Function to add the hidden admin page for replacing media
function media_replacer_admin_menu() {
add_submenu_page(
null, // We don’t want this to appear in the menu
'Replace Media',
'Replace Media',
'upload_files', // Capability needed to access this page
'replace-media',
'media_replacer_replace_file_page'
);
}
add_action('admin_menu', 'media_replacer_admin_menu');
Step 2: Activate the Plugin
After saving the code, go to your WordPress admin area and activate the plugin from the Plugins page. Now, when you go to the Media Library, you’ll see a “Replace File” link next to your PDF files.
Step 3: Replacing a File
Click the “Replace File” link, select your new file, and click the “Replace File” button. The new file will overwrite the old one, and the URL will remain unchanged. No more updating links across your site!
Conclusion
This plugin is a simple yet powerful tool for anyone who frequently updates media files on their WordPress site. It saves time and ensures that your URLs remain consistent, reducing the risk of broken links and improving your site’s overall user experience.
Feel free to download the plugin, modify it to suit your needs, and share it with others who might find it useful!
Download the Media File Replacer Plugin here.