1

For internal purpose, I'm looking for to convert (-) and (escape) sign to (_) automatically when we upload a file (photo,video,audio) on WordPress media library.

Example:

If i try to upload this 2 files :

  • network-picture.png
  • web audio.mp3

I want to have this result on wordpress media library for this 2 files :

  • wp-content/uploads/2018/09/network_picture.jpg
  • wp-content/uploads/2018/09/web_audio.mp3

Right now, if we upload a file with (escape) like (web audio.mp3) you will have this result :

  • wp-content/uploads/2018/09/web-audio.mp3

Thanks.

0

You can use sanitize_file_name hook for this.

function my_sanitize_file_name( $filename ) {
    $chars_table = array(
        ' ' => '_',
        '-' => '_',
    );

    $friendly_filename = preg_replace( array_keys( $chars_table ), array_values( $chars_table ), $filename );

    return strtolower( $friendly_filename );
}
add_filter( 'sanitize_file_name', 'my_sanitize_file_name', 10 );

It will also convert letters to lowercase to avoid conflicts on case-sensitive servers.

  • First, thanks for your reply. I added the code on functions.php. After that, i uploaded the file (normal-picture.png). after the upload, the file name display on the library is (-1). any idea to fix it? – sampaii Sep 17 '18 at 16:20
  • any idea about the issue? – sampaii Sep 24 '18 at 9:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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