最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

uploads - Use wp_handle_upload outside of a POST

programmeradmin1浏览0评论

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

Share Improve this question asked Feb 15, 2022 at 14:57 wpdev215wpdev215 31 bronze badge 1
  • 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
Add a comment  | 

1 Answer 1

Reset to default 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
}
  • 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,

发布评论

评论列表(0)

  1. 暂无评论