skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search