我创建了一个名为“pdf”的自定义帖子类型。我有一个自定义的metabox,用户可以通过wordpress内置媒体上传器上传pdf文件。我需要在这个上传器中限制允许的文件(pdf)。我已经知道如何限制允许的文件:How to set file type in wp_handle_upload?但是上面的链接干扰了所有的上传。有什么提示吗?
谢谢
编辑:我发现了如何在plupload中限制文件类型,所以我解决了一半问题:
add_filter( \'plupload_init\', \'my_plupload_init\', 0, 1 );
function my_plupload_init( $plupload_init ) {
$plupload_init[\'filters\'] = array( array(\'title\' => __( \'Allowed Files\' ), \'extensions\' => \'pdf\') );
return $plupload_init;
}
编辑#2:使用wp\\u handle\\u upload\\u prefilter过滤器不起作用:这是在将图像上载到新帖子后$\\u请求对象中可用的内容:
array
\'type\' => string \'image\' (length=5)
\'tab\' => string \'type\' (length=4)
\'post_id\' => string \'0\' (length=1)
\'_wpnonce\' => string \'375c5f46f2\' (length=10)
\'_wp_http_referer\' => string \'/wp-admin/media-upload.php?post_id=\' (length=37)
\'html-upload\' => string \'Carica media\' (length=12)
没有关于我的自定义帖子类型的信息。id为0,因为帖子尚未保存。
编辑#3:
感谢@TheDeadMusic answer,我在javascript中添加了一行代码。这是我实际使用的非常有效的js代码:
jQuery(document).ready(function($){
// #btn_upload is my custom button
$(\'#btn_upload\').click(function(event){
event.preventDefault();
var backup = window.send_to_editor;
var src=\'\';
//post_id is always set so I can pass it safely to tickbox
var post_id=$(\'#post_ID\').val();
var target=$(\'#pdf_url\');
window.send_to_editor = function(html)
{
//I have to get the link to "original file" from html returned by tickbox
link = $(\'a\',html).attr(\'href\');
$(target).val(link);
tb_remove();
window.send_to_editor=backup; //reset default action
}
//show the uploader
tb_show(\'\', \'media-upload.php?post_id=\'+post_id+\'&TB_iframe=true\');
});
});
最合适的回答,由SO网友:TheDeadMedic 整理而成
function wpse_59621_mimes_filter( $mimes ) {
return array( \'pdf\' => \'application/pdf\' );
}
function wpse_59621_delay_mimes_filter( $value ) {
if ( isset( $_REQUEST[\'post_id\'] ) && get_post_type( $_REQUEST[\'post_id\'] ) === \'my_post_type\' )
add_filter( \'upload_mimes\', \'wpse_59621_mimes_filter\' );
else
remove_filter( \'upload_mimes\', \'wpse_59621_mimes_filter\' );
return $value;
}
add_filter( \'wp_handle_upload_prefilter\', \'wpse_59621_delay_mimes_filter\' );
让我们知道它是如何进行的-这是未经测试的,但我有信心!