Join the Voxel Guide Community!

Get Involved

Rename Images Uploaded to Posts

Description/Instructions

This will rename the image uploaded to the post with the post-title-post-id-filename.extension

If this snippet helped, feel free to buy me a taco :)

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
Copy Code

Let's Chat About this Snippet

Chat Toggle
Voxel Guide AI
Voxel Guide AI
Voxel Guide AI
Voxel Guide AI
Ask me anything about Voxel!
Send
Powered by AI24