I'm writing a script that will prefill my custom post type with posts. Each post has a file (zip or json) as post meta that has to be uploaded to the media folder. The problem is wp_handle_upload needs an array from the $_FILES superglobal as an argument, rather than a context stream to the file. I tried resolving this by moving the file to a temp directory and manually populating the $_FILES global like this-

    $_FILES['tempFile'] = array(
        'name' => pathinfo($file, PATHINFO_FILENAME),
        'type' => mime_content_type($tempFile),
        'tmp_name' => sys_get_temp_dir() . pathinfo($file, PATHINFO_FILENAME),
        'error' => 0,
        'size' => strlen(file_get_contents($tempFile)),

However, I get the error Specified file failed upload test. when wp_handle_upload is called. Is there another method I should be using, or is there something else I'm missing? Thanks

  • are you sure wp_handle_upload is the function you want? No uploading is occurring here, it sounds like you actually want to sideload not upload
    – Tom J Nowell
    Commented Feb 15, 2022 at 15:36

1 Answer 1


There is no uploading occurring here, but you did describe sideloading.

So use media_handle_sideload instead, e.g.

$file_array = [
    'name'     => 'test.jpg',
    'tmp_name' => '/path/to/test.jpg'

$post_id = 0;
$attachment_id = media_handle_sideload( $file_array, $post_id );
if ( is_wp_error( $attachment_id ) ) {
    // ... it failed

There are other functions that build on this, e.g. media_sideload_image which takes the URL of an image, downloads it, and runs it through the sideload functions,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.