使用以下代码,我试图使用WordPress媒体API仅允许上载/选择某些图像类型。所以我在upload\\u mimes上使用add\\u filter来限制允许的mime类型。使用get\\u allowed\\u mime\\u types()可以得到一个仅包含所需mime类型的数组。但是,当我单击“更改图像”按钮时,我仍然可以上载以前未列出的mime类型的文件(如PDF)。我做错了什么?
public static function file_uploader( $element_id = null, $multiple = true )
{
add_filter( \'upload_mimes\', array( \'JBLAB_Utils\', \'images_upload_mimes\' ) );
var_dump( get_allowed_mime_types() );
/**
* outputs:
* array(3) {
* ["jpg|jpeg|jpe"]=>
* string(10) "image/jpeg"
* ["gif"]=>
* string(9) "image/gif"
* ["png"]=>
* string(9) "image/png"
* }
*/
$multiple = ( $multiple === true ) ? \'true\' : \'false\';
wp_enqueue_script(\'jquery\');
wp_enqueue_media();
?>
<div>
<?php
if ( empty( $element_id ) )
{
$element_id = "jblab_uploaded_file_url";
?>
<label for="jblab_uploaded_file_url"><?php _e( \'Image\', \'jblab-radionomy\' ); ?></label>
<input type="text" name="jblab_uploaded_file_url" id="jblab_uploaded_file_url" class="regular-text">
<?php
}
?>
<input type="button" name="jblab_upload_file_upload_btn" id="jblab_upload_upload_btn" class="button-secondary" value="<?php _e( \'Change Image\', \'jblab-radionomy\' ); ?>">
</div>
<script type="text/javascript">
jQuery(document).ready(function($){
$(\'#jblab_upload_upload_btn\').click(function(e) {
e.preventDefault();
var image = wp.media({
title: \'<?php echo str_replace( "\'", "\\\'", __( \'Change Image\', \'jblab-radionomy\' ) ); ?>\',
multiple: <?php echo $multiple; ?>
}).open()
.on(\'select\', function(e){
var uploaded_image = image.state().get(\'selection\').first();
var image_url = uploaded_image.toJSON().url;
<?php
echo "
if ($(\'#$element_id\').is(\'img\')) {
$(\'#$element_id\').attr(\'src\',image_url);
} else {
$(\'#$element_id\').val(image_url);
}
";
?>
});
});
});
</script>
<?php
}
public static function images_upload_mimes ( $mimes = array() )
{
//unset( $mimes );
$mimes = array(
\'jpg|jpeg|jpe\' => \'image/jpeg\',
\'gif\' => \'image/gif\',
\'png\' => \'image/png\',
);
return $mimes;
}