Skip to content

Instantly share code, notes, and snippets.

@filipecsweb
Last active February 7, 2024 00:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save filipecsweb/c3ffa1385826b9eec926 to your computer and use it in GitHub Desktop.
Save filipecsweb/c3ffa1385826b9eec926 to your computer and use it in GitHub Desktop.
Rename WordPress media file name when doing upload
<?php
/**
* Rename file name while doing upload.
*
* @param string $filename The name of the file being uploaded
*
* @return string The sanitized string
*/
function my_custom_file_name( $filename ) {
$info = pathinfo( $filename );
$ext = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
$name = basename( $filename, $ext );
if ( isset( $_REQUEST['post_id'] ) && is_numeric( $_REQUEST['post_id'] ) ) {
$postObj = get_post( $_REQUEST['post_id'] );
$postSlug = sanitize_title( $postObj->post_title );
}
if ( isset( $postSlug ) && ! empty( $postSlug ) && $postSlug != 'rascunho-automatico' ) {
$finalFileName = $postSlug;
} // File name will be the same as the post slug.
else {
$finalFileName = sanitize_title( $name );
} // File name will be the same as the image file name, but sanitized.
return $finalFileName . $ext;
}
add_filter( 'sanitize_file_name', 'my_custom_file_name', 100 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment