我最终得到了这个。解决方案是使用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
, 所以你可以测试一下。