WordPress SVG文件上传如何实现,让WP支持SVG文件上传

发布于 更新于
34,082

默认情况下, WordPress出于安全考虑不支持SVG格式(可缩放矢量图形)文件上传,将下面的代码添到主题functions.php 文件中,保存文件后,就可以在WordPress后台正常上传SVG文件了。

20250429120734942

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);

 

支持作者
如果这篇内容对你有帮助,可以请作者喝杯咖啡
0 点赞
0 收藏
分享
0 讨论
反馈
0 / 600
0 讨论
热门最新
总结
暂无总结