如何让WordPress支持上传SVG格式图片并显示在媒体库中

下面由WordPress教程栏目给大家介绍让WordPress支持上传SVG格式图片并显示在媒体库中的方法,希望对需要的朋友有所帮助!

如何让WordPress支持上传SVG格式图片并显示在媒体库中

因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 "<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 ......

以上就是如何让WordPress支持上传SVG格式图片并显示在媒体库中的详细内容,更多请关注七哩云社其它相关文章!

wordpress教程

Wordpress打开调试模式

2022-6-13 21:38:45

wordpress教程

WordPress 插件、主题与PHP8的兼容性

2022-6-13 21:38:55

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