Wordpress Snippets

Convert WordPress Image Filename To Lowercase

WordPress by default will preserve capitalisation in filename for images. To make filenames lowercase automatically, add the following to the functions.php of your active theme.

/**
 * Convert filename to lowercase
 *
 * @author Arun Basil Lal
 * @refer https://codex.wordpress.org/Plugin_API/Filter_Reference/wp_handle_upload_prefilter
 */
function prefix_convert_filename_to_lowercase( $file ) {
	
	$image_extensions = array (
		'image/jpeg', 'image/gif', 'image/png', 'image/bmp', 'image/tiff', 'ico'
	);
	
	// Return if file is not an image file
	if ( ! in_array($file['type'],$image_extensions) ) {
		return $file;
	}
	
	$image_extension = pathinfo( $file['name'] );
	$image_name 	 = strtolower( $image_extension['filename'] );
	$file['name'] 	 = $image_name . '.' . $image_extension['extension'];
	
	return $file;
}
add_filter('wp_handle_upload_prefilter', 'prefix_convert_filename_to_lowercase', 20 );

Hire Us. Or just say Hi!
Need a job? Apply to get one.