WordPress支持上传SVG图片并显示在媒体库中

WordPress1 667阅读模式

因SVG格式图片特性,可能会被插入恶意代码,网站容易被攻击,所以出于安全考虑WordPress默认不支持SVG格式图片上传,另外不像网上说SVG格式图片有那么高的应用价值,除了一些网页上的小图标可以使用SVG图片外,正常的彩色图片,如果使用SVG格式毫无优势可言。不过有时还确实需要这个SVG图片比如我主题的LOGO图片,如果使用PNG图片在手机上不是很清晰,采用SVG格式则无此问题。

WordPress支持上传SVG图片并显示在媒体库中

WordPress支持上传SVG图片并显示在媒体库中

如何让WordPress支持上传SVG格式图片?可以将下代码添加当前主题函数模板functions.php中:

让WordPress支持上传SVG,并只管理员有此权限

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

媒体库列表模式显示SVG图片

// 媒体库列表模式显示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图片,下面的代码可以实现:

// 媒体库网格模式显示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);

另一个相对代码较少的支持媒体库网格模式显示SVG图片代码,不过如果开启调试模式会有错误提示,但不影响使用。

// 媒体库网格模式显示SVG图片
function zm_svg_metadata($data, $post_id) {
	$data = array(
		'sizes' => array(
			'large' => array(
				'file' => pathinfo(wp_get_attachment_url($post_id), PATHINFO_BASENAME)
			)
		)
	);
	return $data;
}
add_filter('wp_get_attachment_metadata', 'zm_svg_metadata', 10, 2);

至于加这个功能用于什么,那要看你用的主题是否有这个功能需要了,直接FTP上传后获取链接也一样在网页中使用。

嫌折腾代码麻烦,可以使用下面的相关插件:

  • SVG Support
  • Enable SVG
  • Safe SVG(据说该插件可以检测并去除SVG中的恶意代码,与250+110有的一拼)
  • WP SVG images
  • Easy SVG Support
  • Enable SVG Uploads
  • ......

 

 

本站文章大部分始于原创,用于个人学习记录,可能对您有所帮助,仅供参考!

weinxin
我的微信
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
  • WordPress
  • functions.php
    • 白杨博客
      白杨博客 2

      感谢分享

    匿名

    发表评论

    匿名网友
    :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

    拖动滑块以完成验证