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

WordPress博客添加“返回顶部”按钮

默认情况下, 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图片
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);

什么是SVG

SVG是”Scalable Vector Graphics”的简称。中文可以理解成“可缩放矢量图形”。这个概念对于设计师来讲一点不陌生,但对于码农来讲,总是没有设计师们理解的那么透彻。其实码农们也没必要理解的那么透彻,只需要知道它是web页中的矢量图即可。

WP优化

广告小工具 移植自日主题RIPRO

2021-2-7 12:05:18

WP优化

WordPress:关注微信公众号获取验证码

2021-2-22 13:28:52

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索