I am trying to rename upload filenames match the Post Title.
This other thread shows how to rename to hash:
Rename files during upload within WordPress backend
Using this code:
function make_filename_hash($filename) {
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$name = basename($filename, $ext);
return md5($name) . $ext;
}
add_filter('sanitize_file_name', 'make_filename_hash', 10);
Does anyone know the code to rename the file to match Post Title.extension?
barakadam’s answer is almost correct, just a little correction based on the comment I left below his answer.
Explanation of code:
Lets assume you upload a file with the original filename called
picture one.jpgto a post called “My Holiday in Paris/London”.When you upload a file, WordPress removes special characters from the original filename using the
sanitize_file_name()function.Right at the bottom of the function is where the filter is.
At this point, $filename would be
picture-one.jpg. Because we usedadd_filter(), our new_filename() function will be called with $filename aspicture-one.jpgand $filename_raw aspicture one.jpg.Our new_filename() function then replaces the filename with the post title with the original extension appended. If we stop here, the new filename
$newwould end up beingMy Holiday in Paris/London.jpgwhich all of us know is an invalid filename.Here is when we call the sanitize_file_name function again. Note the conditional statement there. Since
$new != $filename_rawat this point, it tries to sanitize the filename again.sanitize_file_name()will be called and at the end of the function,$filenamewould beMy-Holiday-in-Paris-London.jpgwhile$filename_rawwould still beMy Holiday in Paris/London.jpg. Because of theapply_filters(), ournew_filename()function runs again. But this time, because$new == $filename_raw, thats where it ends.And
My-Holiday-in-Paris-London.jpgis finally returned.