Reputation: 2398
Suppose I uploaded a media file for eg image, and its name is example_123_56737_303030.png
but before upload I want this name of the image to be changed as any thing of my choice (best will be post_id of this attachment) so it looks like 122.png (122 is the post_id of this attachment).
Now the things that needs to be achieved is :
_wp_attached_file
, _wp_attachment_metadata
in wp_post_meta
table should be as per the new name.Upvotes: 0
Views: 2545
Reputation: 731
Put below code into your functions.php
function handle_uploadedimage($arr) {
// Get the parent post ID, if there is one
if( isset($_REQUEST['post_id']) ) {
$post_id = $_REQUEST['post_id'];
} else {
$post_id = false;
}
// Only do this if we got the post ID--otherwise they're probably in
// the media section rather than uploading an image from a post.
if($post_id && is_numeric($post_id)) {
// Get the post slug
$post_obj = get_post($post_id);
// If we find post
if(!empty($post_obj->post_name)) {
$post_slug = $post_obj->post_name;
$random_number = rand(10000,99999);
$ext = pathinfo($arr['name'], PATHINFO_EXTENSION);
//Write your logic to remove any special characters from file name
$arr['name'] = $post_slug . '-' . $random_number . '.'.$ext;
}
}
return $arr;
}
add_filter('wp_handle_upload_prefilter', 'handle_uploadedimage', 1, 1);
You can also try below version
function handle_uploadedimage($arr) {
$random_number = md5(rand(10000,99999));
$ext = pathinfo($arr['name'], PATHINFO_EXTENSION);
$arr['name'] = $random_number .'.'.$ext;
return $arr;
}
add_filter('wp_handle_upload_prefilter', 'handle_uploadedimage', 1, 1);
You can also try this plugin wordpress.org/plugins/file-renaming-on-upload/screenshots which will be better I guess
Upvotes: 1