### [WordPress SVG文件上传如何实现,让WP支持SVG文件上传](https://www.prosaas.cn/article/30921) **Published:** 2025-04-18T04:24:48 **Author:** 5201314 **Excerpt:** 默认情况下, WordPress出于安全考虑不支持SVG格式(可缩放矢量图形)文件上传,将下面的代码添到主题f… > 默认情况下, **WordPress**出于安全考虑不支持SVG格式(可缩放矢量图形)文件上传,将下面的代码添到主题functions.php 文件中,保存文件后,就可以在WordPress后台正常上传SVG文件了。 ![20250429120734942](https://zhiqipro.oss-cn-beijing.aliyuncs.com/2025/04/20250429120734942.png "20250429120734942") ```none 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图片 ```none // 只允许管理员上传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); ``` **Tags:** copy, function, http, number, php, register, ul, xml **Categories:** WordPress ---