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



图片[1]-纯代码实现WordPress媒体库支持上传SVG图片文件并显示-卷生活九二零

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

// 只允许管理员上传 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 图片文件的功能,则可以只添加代码 1 即可,但是无法在媒体库列表模式中显示 SVG 图片。如果想要同时实现上传 SVG 文件和显示 SVG 图片的话,则需要将代码 1 和代码 2 都添加到当前主题函数模板 functions.php 文件中即可。 WordPress 5.5.3 测试代码 1 和代码 2 都可以实现。

支付宝扫码打赏 微信打赏

如果我的文章对你有帮助,欢迎移至上方按钮打赏

© 版权声明
THE END
点赞0
分享