默认情况下, WordPress出于安全考虑不支持SVG格式(可缩放矢量图形)文件上传,将下面的代码添到主题functions.php 文件中,保存文件后,就可以在WordPress后台正常上传SVG文件了。
function myplugin_activate() {
$upload = wp_upload_dir();
$upload_dir = $upload['basedir'];
$upload_dir = $upload_dir . '/mypluginfiles';
if (! is_dir($upload_dir)) {
mkdir( $upload_dir, 0700 );
}
}
register_activation_hook( __FILE__, 'myplugin_activate' );
还有种方法就是只允许管理员上传SVG图片
// 只允许管理员上传SVG图片
if (current_user_can( 'manage_options' )) {
add_filter('upload_mimes', function ($mimes) {
$mimes['svg'] = 'image/svg+xml';
return $mimes;
});
}
// 媒体库网格模式显示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文件上传如何实现,让WP支持SVG文件上传
文章链接:https://www.prosaas.cn/30921.html
更新时间:2025年04月29日
声明: 本站大部分内容均收集于网络!若内容若侵犯到您的权益,请发送邮件至:973664285@qq.com我们将第一时间处理! 资源所需价格并非资源售卖价格,是收集、整理、编辑详情以及本站运营的适当补贴,并且本站不提供任何免费技术支持。 所有资源仅限于参考和学习,版权归原作者所有,更多请阅读知企PROSAAS协议声明:本文由5201314发布,本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。