Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I check the below answer to rename files during upload and tries to change it to something like postid_originalfilename.jpg but failed. Any help?

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);

http://stackoverflow.com/questions/11586284/rename-files-on-upload-in-wordpress-3-4-1

share|improve this question

1 Answer 1

up vote 1 down vote accepted

If you want to use the above sanitize_file_name filter, you could try this:

function make_filename_hash($filename) {

    if( isset($_REQUEST['post_id']) ) {
        $post_id =  (int)$_REQUEST['post_id'];
    }else{
        $post_id=0;
    }

    $info = pathinfo($filename);
    $ext  = empty($info['extension']) ? '' : '.' . $info['extension'];
    $name = basename($filename, $ext);

    if($post_id>0){
        return $post_id."_".$name . $ext;
    }else{
        return $name . $ext;
    }
}
add_filter('sanitize_file_name', 'make_filename_hash', 10);

where for example image.jpg is changed to 123_image.jpg where 123 is the parent post id.

share|improve this answer
    
That's awesome and works like a charm! Thank you very much for the quick reply, it's really helpful! –  Milo Mar 9 '13 at 21:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.