腾讯云服务器优惠活动华纳云香港服务器

纯代码实现WordPress媒体库支持上传SVG图片文件并显示

WordPress主题推荐

为了站点数据安全 WordPress 默认情况下不允许直接在后台上传 SVG 图片文件的,如果直接上传将会显示“抱歉,由于安全原因,这个文件类型不受支持。”错误提示而无法上传。其实,有很多插件可以解决这个 WordPress 无法上传 SVG 文件和显示的问题,如 Safe SVGEasy SVG SupportWP SVG imagesSVG Support 插件等,不过有些站长比较喜欢用代码实现而不喜欢插件,具体实现方法很简单,只需要将以下代码添加当前主题函数模板 functions.php 文件中即可。

代码 1:让 WordPress 支持上传 SVG 文件而且只有管理员有此权限

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

代码 2:让媒体库列表模式显示 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);

以上两段代码均来自@知更鸟WordPress 支持上传 SVG 图片并显示在媒体库中

如果你想让你的 WordPress 站点有上传 SVG 图片文件的功能,则可以只添加代码 1 即可,但是无法在媒体库列表模式中显示 SVG 图片。如果想要同时实现上传 SVG 文件和显示 SVG 图片的话,则需要将代码 1 和代码 2 都添加到当前主题函数模板 functions.php 文件中即可。老古用 WordPress 5.5.3 测试代码 1 和代码 2 都可以实现。

本文地址:https://boke112.com/post/8448.html

赞 (0) 打赏
版权声明:本文为原创文章,版权归 boke112百科 所有,欢迎分享本文,转载请保留出处!发布此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请联系我们,确认后马上更正或删除,谢谢!
wu