Rename files during upload within Wordpress

2019-02-25 01:03发布

问题:

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?

回答1:

barakadam's answer is almost correct, just a little correction based on the comment I left below his answer.

function new_filename($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', 'new_filename', 10, 2);

Explanation of code:

Lets assume you upload a file with the original filename called picture one.jpg to 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.

// line 854 of wp-includes/formatting.php
return apply_filters('sanitize_file_name', $filename, $filename_raw);

At this point, $filename would be picture-one.jpg. Because we used add_filter(), our new_filename() function will be called with $filename as picture-one.jpg and $filename_raw as picture 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 $new would end up being My Holiday in Paris/London.jpg which 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_raw at this point, it tries to sanitize the filename again.

sanitize_file_name() will be called and at the end of the function, $filename would be My-Holiday-in-Paris-London.jpg while $filename_raw would still be My Holiday in Paris/London.jpg. Because of the apply_filters(), our new_filename() function runs again. But this time, because $new == $filename_raw, thats where it ends.

And My-Holiday-in-Paris-London.jpg is finally returned.



回答2:

Something like this? (considering $post is your post variable, make it global):

function new_filename($filename) {
    global $post;
    $info = pathinfo($filename);
    $ext  = empty($info['extension']) ? '' : '.' . $info['extension'];
    return $post->post_title . $ext;
}
add_filter('sanitize_file_name', 'new_filename', 10);

Did I understand you?