MaxHarti
MaxHarti

Reputation: 11

Wordpress - Media Image Slug/Permalink - Change Renaming Upload Logic

When I upload an image to Wordpress with the name:

I would need the format:

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

Upvotes: 0

Views: 442

Answers (2)

joshmoto
joshmoto

Reputation: 5088

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

Upvotes: 0

Akhtarujjaman Shuvo
Akhtarujjaman Shuvo

Reputation: 690

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.

Upvotes: 1

Related Questions