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
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
1 Answer
Reset to default 1There 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
}
- https://developer.wordpress.org/reference/functions/media_handle_sideload/
- based on https://developer.wordpress.org/reference/functions/media_handle_sideload/#comment-983
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,
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