You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 lines
2.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
/**
* 媒体配置文件
* 管理文件上传、SVG支持、媒体库显示等功能
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
/**
* 允许上传SVG图片和PDF文档
* 扩展WordPress默认允许的文件类型
* @param array $mimes 当前允许的MIME类型数组
* @return array 扩展后的MIME类型数组
*/
function allow_additional_file_types($mimes) {
// 确保 $mimes 是数组
if (!is_array($mimes)) {
return $mimes;
}
$mimes['svg'] = 'image/svg+xml';
$mimes['pdf'] = 'application/pdf';
return $mimes;
}
add_filter('upload_mimes', 'allow_additional_file_types');
/**
* 修复SVG图片在媒体库中的显示
* 添加CSS样式确保SVG图片正确显示
*/
function fix_svg_display() {
echo '<style>
.attachment-266x266, .thumbnail img {
width: 100% !important;
height: auto !important;
}
</style>';
}
add_action('admin_head', 'fix_svg_display');
/**
* 为SVG添加安全检查
* 检查SVG文件是否包含恶意脚本代码
* @param array $file 上传的文件信息数组
* @return array 处理后的文件信息数组
*/
function check_svg_file($file) {
if ($file['type'] === 'image/svg+xml') {
$svg_content = file_get_contents($file['tmp_name']);
// 检查是否包含危险的脚本标签
if (strpos($svg_content, '<script') !== false ||
strpos($svg_content, 'javascript:') !== false ||
strpos($svg_content, 'onload=') !== false ||
strpos($svg_content, 'onerror=') !== false) {
$file['error'] = '出于安全考虑不允许上传包含脚本的SVG文件。';
}
}
return $file;
}
add_filter('wp_handle_upload_prefilter', 'check_svg_file');
/**
* 在媒体库中正确显示SVG缩略图
* 为SVG文件生成适当的缩略图信息
* @param array $response 附件响应数据
* @param object $attachment 附件对象
* @param array $meta 附件元数据
* @return array 处理后的响应数据
*/
function svg_media_thumbnails($response, $attachment, $meta) {
// 确保 $response 是数组
if (!is_array($response)) {
return $response;
}
if (isset($response['type']) && isset($response['subtype']) &&
$response['type'] === 'image' && $response['subtype'] === 'svg+xml') {
$response['image'] = array(
'src' => $response['url'],
'width' => 150,
'height' => 150,
);
$response['thumb'] = array(
'src' => $response['url'],
'width' => 150,
'height' => 150,
);
$response['sizes'] = array(
'full' => array(
'url' => $response['url'],
'width' => 150,
'height' => 150,
'orientation' => 'landscape'
)
);
}
return $response;
}
add_filter('wp_prepare_attachment_for_js', 'svg_media_thumbnails', 10, 3);
?>