Home > Mobile >  Wordpress - Media Image Slug/Permalink - Change Renaming Upload Logic
Wordpress - Media Image Slug/Permalink - Change Renaming Upload Logic

Time:12-22

When I upload an image to Wordpress with the name:

  • Image20_O9KA M 21.jpg Wordpress will change the permalink to:
  • Image20_09KA-M-21.jpg

I would need the format:

  • Image_09KA_M_21.jpg

How can I get that format automatically when uploading new images?

CodePudding user response:

You can try below filter.

function prefix_file_rename_on_upload( $filename ) {
    return str_replace('Image20', 'Image', $filename)
}
add_filter( 'sanitize_file_name', 'prefix_file_rename_on_upload', 10 );

Not tested.

CodePudding user response:

Same method as @Akhtarujjaman Shuvo but replacing the $filename whitespaces and hyphens with underscores before returning through the sanitize_file_name filter...

function sanitize_file_name_with_underscores($filename) {
    return str_replace([' ','-'], ['_','_'], $filename)
}
add_filter('sanitize_file_name', 'sanitize_file_name_with_underscores', 10 );

In theory (not tested)...

  • Uploaded filename: Image20_O9KA M 21.jpg

  • Filename result: Image20_O9KA_M_21.jpg

  • Related