WordPress wp_enqueue_media()upload_mimes没有过滤

时间:2015-06-18 01:18:06

标签: wordpress-plugin wordpress

使用以下代码,我尝试仅允许使用WordPress媒体API上传/选择某些图像类型。所以我在upload_mimes上使用add_filter来限制允许的mime类型。使用get_allowed_mime_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;
}

1 个答案:

答案 0 :(得分:0)

好的,所以我找到了解决问题的方法。

我不得不将add_filter移到调用上传API的函数之外。如果有人遇到同样的问题,请在此过程中尽快尝试add_filters,这应该可以解决问题。