Snippets / PHP
Rename Images Uploaded to Posts
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');
Discussion 2
Ask a question or share how you used this.
Interesting. So, this works only when uploading in the front form? Or also when working in the back end (wp-admin)?
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']
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.