### [如何让WordPress支持上传SVG格式图片并显示在媒体库中](https://www.prosaas.cn/article/8799) **Published:** 2020-12-09T05:53:05 **Author:** 5201314 **Excerpt:** 下面由WordPress教程栏目给大家介绍让WordPress支持上传SVG格式图片并显示在媒体库中的方法,希… 下面由**WordPress教程**栏目给大家介绍让WordPress支持上传SVG格式图片并显示在媒体库中的方法,希望对需要的朋友有所帮助! ![](//zhiqipro.oss-cn-beijing.aliyuncs.com/2023/12/20231212131632924.jpg) 因SVG格式图片特性,可能会被插入恶意代码,网站容易被攻击,所以出于安全考虑WordPress默认不支持SVG格式图片上传,另外不像网上说SVG格式图片有那么高的应用价值,除了一些网页上的小图标可以使用SVG图片外,正常的彩色图片,如果使用SVG格式毫无优势可言。不过有时还确实需要这个SVG图片比如我主题的LOGO图片,如果使用PNG图片在手机上不是很清晰,采用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 ""; }); 网上有很多以上类似的代码,但都不支持媒体库网格模式显示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 ...... 以上就是如何让WordPress支持上传SVG格式图片并显示在媒体库中的详细内容,更多请关注知企PROSAAS其它相关文章! **Tags:** php, WordPress, 函数模板 **Categories:** WordPress ---