WordPress 添加 SVG 图片支持,并在媒体库显示

SVG(Scalable Vector Graphics 可缩放矢量图形)这一格式在当下互联网前端已经成为主流,作为矢量图形格式,它可以无损缩放,还可以方便的通过代码编辑修改颜色等。

而在 WordPress 中默认并不支持 SVG 格式上传,只需要将下面代码添加到当前主题的 functions.php 文件中,保存之后,就能正常在后台编辑中上传 SVG 文件,文件也能在媒体库中正确显示预览。

// 只允许管理员上传SVG图片
if (current_user_can( 'manage_options' )) {
	add_filter('upload_mimes', function ($mimes) {
		$mimes['svg'] = 'image/svg+xml';
		return $mimes;
	});
}

// 媒体库列表模式显示SVG图片
add_action('admin_head', function () {
	echo "<style>table.media .column-title .media-icon img[src*='.svg']{width: 100%;height: auto;}.components-responsive-wrapper__content[src*='.svg'] {position: relative;}</style>";
});

// 媒体库网格模式显示SVG图片
function zm_display_svg_media($response, $attachment, $meta){
	if($response['type'] === 'image' && $response['subtype'] === 'svg+xml' && class_exists('SimpleXMLElement')){
		try {
			$path = get_attached_file($attachment->ID);
			if(@file_exists($path)){
				$svg                = new SimpleXMLElement(@file_get_contents($path));
				$src                = $response['url'];
				$width              = (int) $svg['width'];
				$height             = (int) $svg['height'];
				$response['image']  = compact( 'src', 'width', 'height' );
				$response['thumb']  = compact( 'src', 'width', 'height' );
 
				$response['sizes']['full'] = array(
					'height'        => $height,
					'width'         => $width,
					'url'           => $src,
					'orientation'   => $height > $width ? 'portrait' : 'landscape',
				);
			}
		}
		catch(Exception $e){}
	}
	return $response;
}
add_filter('wp_prepare_attachment_for_js', 'zm_display_svg_media', 10, 3);

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注