Skip to content

Snippets / PHP

PHP

Rename Images Uploaded to Posts

D Donald McGuinn · 505 views · Updated 1 year ago
This will rename the image uploaded to the post with the post-title-post-id-filename.extension
function custom_update_uploaded_file_name($file) {
if (isset($_POST['post_id']) && $_POST['post_id'] != 0) {
$post_id = intval($_POST['post_id']);
$post = get_post($post_id);

if ($post && !in_array($post->post_type, ['post', 'page'])) { // Modify for custom post types only
$post_title = sanitize_title($post->post_title);
$original_filename = $file['name'];
$file_ext = pathinfo($original_filename, PATHINFO_EXTENSION);
$file_name_only = pathinfo($original_filename, PATHINFO_FILENAME);

// Construct new file name
$new_filename = "{$post_title}-{$post_id}-{$file_name_only}.{$file_ext}";

// Update file name in the upload process
$file['name'] = $new_filename;
}
}

return $file;
}

add_filter('wp_handle_upload_prefilter', 'custom_update_uploaded_file_name');
PHP · 23 lines

Discussion 2

Ask a question or share how you used this.

Log in to join the discussion.
rrvoigt 1 year ago

Interesting. So, this works only when uploading in the front form? Or also when working in the back end (wp-admin)?

Donald McGuinn 1 year ago

I tested from the backend but I should test the front end too.

Josi Schneider 1 year ago

Nice one! Will this also add numeration at the end of the file name, if there are multiple images uploaded to that post? Will we need to add our custom post type key(s) here like this? ['post', 'page', 'cpt1']

Donald McGuinn 1 year ago

it still retains the original file name. so unless youre uploading 10 images named image.jpg, it will be fine. even so, wordpress will automatically add -1 to the end of an image if you upload one with the same name. No you wont need to. it will do it for all custom posts out of the box. i tried it on the voxel guide website post type without changing anything and it worked perfectly.

Voxel Guide assistant
Ask about snippets, addons & how-tos

Hey — how can I help?

I can dig through the library for snippets, addons, and tutorials.

AI can be wrong — double-check anything important.