You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改WordPress wp.media上传器以支持PDF、Word等文档?

问题

我通过以下代码创建了一个WordPress媒体上传器,但该上传器仅支持图片格式。请问如何修改代码,使其支持PDF、Word等文档类文件?

file_frame = wp.media.frames.file_frame = wp.media({ 
    title: $( this ).data( 'uploader_title' ), 
    frame: 'select', 
    button: { 
        text: $( this ).data( 'uploader_button_text' ), 
    }, 
    multiple: false // set this to true for multiple file selection 
}); 

感谢您的帮助。


解决方案

嘿,这个调整其实超简单!你只需要在wp.media的配置对象里加一个library属性,指定允许的文件类型,就能让上传器支持PDF、Word这类文档了。我给你两种常用的配置方式:

方式1:精确指定MIME类型

如果你想精准控制允许的文件类型,可以直接列出对应的MIME类型数组。比如要保留图片支持,同时添加PDF、Word(包括.doc和.docx),代码修改后是这样的:

file_frame = wp.media.frames.file_frame = wp.media({ 
    title: $( this ).data( 'uploader_title' ), 
    frame: 'select', 
    button: { 
        text: $( this ).data( 'uploader_button_text' ), 
    }, 
    multiple: false, // set this to true for multiple file selection
    library: {
        type: [
            'image/jpeg', 
            'image/png', 
            'image/gif',
            'application/pdf',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        ]
    }
}); 

方式2:按文件类别筛选

要是你想更宽泛地允许所有文档类文件,直接用category参数就行,比如:

file_frame = wp.media.frames.file_frame = wp.media({ 
    title: $( this ).data( 'uploader_title' ), 
    frame: 'select', 
    button: { 
        text: $( this ).data( 'uploader_button_text' ), 
    }, 
    multiple: false, // set this to true for multiple file selection
    library: {
        category: 'documents' // 会包含PDF、Word、Excel等各类常见文档
    }
}); 

如果需要同时支持图片和文档,把category改成数组就行:category: ['images', 'documents'],这样上传器里就会同时显示这两类文件啦。

额外注意事项

WordPress默认可能限制了某些文件类型的上传权限,所以如果配置完前端代码还是没法上传文档,你需要在后端解锁这些类型。可以把下面的代码加到主题的functions.php或者wp-config.php里:

// 允许站点上传PDF、Word文档
function allow_custom_mime_types( $mimes ) {
    $mimes['pdf'] = 'application/pdf';
    $mimes['doc'] = 'application/msword';
    $mimes['docx'] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
    return $mimes;
}
add_filter( 'upload_mimes', 'allow_custom_mime_types' );

这样就能确保你的站点允许这些文件类型的上传了!


内容的提问来源于stack exchange,提问作者Bryan L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:25:58