How to Allow SVG Uploads in WordPress Without Plugins

In this WordPress tutorial, you’ll learn how to enable SVG file uploads on your website without using plugins. SVG (Scalable Vector Graphics) files are popular for their scalability and resolution independence but require careful handling due to potential security risks. We’ll guide you through the process of enabling SVG uploads safely, restricting this feature to administrators using the manage_options capability.

Before proceeding with any customizations in WordPress, it’s essential to set up a child theme. A child theme acts as a safe and efficient way to make modifications without affecting the parent theme. If you haven’t set up a child theme yet, follow this tutorial on How to Create a Child Theme for Customization. It will guide you through the process and ensure that your customizations remain intact even after theme updates.

Customize functions.php in Your Child Theme

Begin by opening your WordPress child theme’s functions.php file. This file acts as the nerve center for tailoring your theme’s functionality. You have the option to edit it directly within the Theme Editor in your WordPress dashboard. For more advanced customization, utilize an external code editor in conjunction with FTP (File Transfer Protocol). Simply insert the provided code snippet at the end of the functions.php file to implement the desired functionality.

add_filter(
	'upload_mimes',
	function ( $upload_mimes ) {
		if ( current_user_can( 'manage_options' ) ) {
			$upload_mimes['svg']  = 'image/svg+xml';
			$upload_mimes['svgz'] = 'image/svg+xml';
		}
		return $upload_mimes;
	}
);
Code language: PHP (php)

Explanation:
This code snippet adds a filter to upload_mimes, allowing SVG (image/svg+xml) and SVGZ (image/svg+xml) files to be uploaded. It checks if the current user has the ‘manage_options’ capability (typically administrators), ensuring that only administrators can upload SVG files.

Validate and Sanitize SVG Files

While the above code allows SVG uploads for administrators, it’s crucial to validate and sanitize SVG files to prevent security vulnerabilities. Add the following function in your functions.php file:

// Validate and sanitize SVG files.
function sanitize_svg_upload( $file ) {
	$filetype = wp_check_filetype( $file, null );

	if ( 'image/svg+xml' === $filetype['type'] ) {
		$svg_content = file_get_contents( $file );

		// Remove potentially harmful code from SVG content.
		$svg_content = preg_replace( '/<script\b[^>]*>(.*?)<\/script>/is', '', $svg_content );
		$svg_content = preg_replace( '/<!ENTITY(.*?)>/is', '', $svg_content );
		$svg_content = preg_replace( '/<!DOCTYPE(.*?)>/is', '', $svg_content );

		// Allow only specific SVG attributes.
		$allowed_attributes = array( 'width', 'height', 'viewBox', 'xmlns' );
		$svg_content        = preg_replace( '/<svg(.*?)>/is', '<svg$1>', $svg_content );
		$svg_content        = preg_replace_callback(
			'/<svg(.*?)>/is',
			function ( $matches ) use ( $allowed_attributes ) {
				$attributes = preg_replace( '/([a-zA-Z\-]+)="(.*?)"/is', '$1="$2"', $matches[1] );
				$attributes = strip_tags( $attributes, '<' . implode( '><', $allowed_attributes ) . '>' );
				return '<svg ' . $attributes . '>';
			},
			$svg_content
		);

		// Save the sanitized content back to the file.
		file_put_contents( $file, $svg_content );
	}

	return $file;
}

add_filter( 'wp_handle_upload_prefilter', 'sanitize_svg_upload' );
Code language: PHP (php)

Explanation:
This code snippet defines the sanitize_svg_upload function, which sanitizes SVG files before they are uploaded to the server. It removes potentially harmful code (such as <script> tags) from the SVG content and allows only specific SVG attributes (width, height, viewBox, xmlns) for added security. The sanitized content is then saved back to the file before the upload process completes. This function is hooked into wp_handle_upload_prefilter, ensuring that the sanitization process occurs before the file is handled by WordPress.

That’s it! Allowing SVG uploads in WordPress without plugins is a powerful capability, but it demands careful handling due to security concerns. By following these steps, you can enable SVG uploads for administrators while ensuring the uploaded SVG files are properly validated and sanitized, enhancing the security of your website.

Leave your feedback and help us improve ๐Ÿถ

We hope you found this article helpful! If you have any questions, feedback, or spot any errors, please let us know in the comments. Your input is valuable and helps us improve. If you liked this article, please consider sharing it with others. And if you really enjoyed it, you can show your support by buying us a cup of coffee โ˜•๏ธ or donating via PayPal ๐Ÿ’ฐ.

More free knowledge, because why not?

Your thoughts matter, leave a reply ๐Ÿ’ฌ

Your email address will not be published. Required fields are marked *