Last active
September 7, 2024 19:22
-
-
Save filipecsweb/c3ffa1385826b9eec926 to your computer and use it in GitHub Desktop.
Rename WordPress media file name when doing upload
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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