sanitize_file_name

Home » Hooks » sanitize_file_name

The sanitize_file_name hook is a filter that WordPress uses to sanitize file names before they are saved to the database. It is a critical hook because it helps to prevent file names that could cause issues with the operating system or web server.

The sanitize_file_name hook can be used to modify the file name before it is saved to the database. This can be useful if you want to change the file name to ensure it is unique or to add additional information to the file name.

The sanitize_file_name hook accepts two parameters: $filename and $filename_raw. The $filename parameter is the sanitized file name that will be saved to the database, and the $filename_raw parameter is the original file name before it was sanitized.

Here is an example usage code for the sanitize_file_name hook:

function myplugin_sanitize_file_name( $filename, $filename_raw ) {
    // Add a custom prefix to the file name
    $prefix = 'myprefix_';
    $filename = $prefix . $filename;
    return $filename;
}
add_filter( 'sanitize_file_name', 'myplugin_sanitize_file_name', 10, 2 );

In this example, we are adding a custom prefix to the sanitized file name. The prefix is defined as "myprefix", and we are appending it to the beginning of the file name. This will ensure that all file names saved to the database have the prefix "myprefix".

Overall, the sanitize_file_name hook is an essential filter that helps to ensure that file names are safe and compatible with the web server and operating system.

Learn More on WordPress.org

WordPress snippets using the sanitize_file_name hook

Register an account to save your snippets or go Pro to get more features.