如何在程序化上传图片时触发wp_Handle_Upload_preFilter过滤器?

时间:2019-04-02 作者:Lucas Bustamante

我正在清理上载的SVG文件wp_handle_upload_prefilter, 示例:

// Example code
add_filter( \'wp_handle_upload_prefilter\', function($file) {
    if ( $file[\'type\'] === \'image/svg+xml\' ) {
        $this->sanitize( $file[\'tmp_name\'] );
    }
} );
它适用于通过媒体库上载的文件,但是,如果文件是通过编程方式上载的,则不会通过过滤器。

我想通过编程上传图像的原因是出于测试目的。我正在上载文件wp_upload_bits 功能:

$upload = wp_upload_bits( \'xss.svg\', null, file_get_contents( $this->svg_path ) );
$uploaded_svg_contents = file_get_contents( $upload[\'file\'] );

$this->assertFalse( $upload[\'error\'] );
$this->assertNotContains( \'<script\', $uploaded_svg_contents );
如何通过编程上传媒体文件wp_handle_upload_prefilter 滤器

1 个回复
SO网友:Lucas Bustamante

我最终得到了这个。解决方案是使用wp_handle_upload() 作用很明显,当我想起来的时候。。。

function handle_upload( string $path ): array {
    $filename        = basename( $path );
    $random_filename = rand( 0, 1000 ) . $filename;
    $tmp_path        = str_replace( $filename, $random_filename, $path );

    /** Create a temporary copy of the original file, since it will be moved during the upload process */
    copy( $path, $tmp_path );

    if ( file_exists( $tmp_path ) ) {
        $_files_mimic = [
            \'name\'     => $random_filename,
            \'type\'     => \'image/svg+xml\',
            \'tmp_name\' => $tmp_path,
            \'error\'    => 0,
            \'size\'     => filesize( $tmp_path ),
        ];

        return wp_handle_upload( $_files_mimic, [
            \'action\'    => \'test_svg_upload\',
            \'test_form\' => false,
        ] );
    } else {
        throw new RuntimeException( \'Could not copy test file from \' . $path . \' to \' . $tmp_path );
    }
}
用法:

$upload_response = handle_upload(\'path/to/my/image.jpg\');
现在如果您调试$upload_response[\'file\'], 您的媒体应该由wp_handle_upload_filter, 所以你可以测试一下。

相关推荐

Yoast SEO过滤器钩子wpseo_sitemap_urlimages何时启动?

我正在尝试将一个简单的函数附加到Yoast SEO过滤器挂钩wpseo_sitemap_urlimages 并让函数运行,但我不能这样做。我的代码是:function tp_filter_wpseo_sitemap_urlimages($images, $post_id) { error_log(\"test message\"); return $images; } add_filter(\'wpseo_sitemap_urlimages\', \'tp_