Hello readres today we will discuss about "How to Rename files during upload within Wordpress backend".
There are many hook function to remane file in uploading time in wordpress. We will use the sanitize_file_name hopok function.
Suppose user want to upload a file(new image.jpg) to a post called "About us". Our hook function run and make changes in the file name like About-us.jpg and our remane_file() function runs again. It will come again in if condition to check $new == $filename_raw or not, if($new == $filename_raw) then it will be end.
<?php
function remane_file($filename, $filename_raw) {
global $post;
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$new = $post->post_title . $ext;
// the if is to make sure the script goes into an indefinate loop
if( $new != $filename_raw ) {
$new = sanitize_file_name( $new );
}
return $new;
}
add_filter('sanitize_file_name', 'remane_file', 10, 2);
?>
0 Comment(s)