I am creating an image on the server and storing it in a tmp folder. I would like to run a php file that takes this image, stores it in the default media directory structure and attaches it to a post while creating appropriate thumbnails. media_handle_upload seems to require an upload POST request to work with. Is it possible to make it work on a local image in a non-POST context? Thanks.
1 Answer
You want media_handle_sideload()
Handles a side-loaded file in the same way as an uploaded file is handled by media_handle_upload().
// Array similar to a $_FILES upload array.
$file_array = array(
'name' => 'filename.jpg',
'tmp_name' => 'path/to/filename.jpg',
);
// Post ID to attach upload to, 0 for none.
$post_id = 0;
$attachment_id = media_handle_sideload( $file_array, $post_id );
-
1Important to note that your file might get moved from
path/to/filename.jpg
to your uploads folder. Commented Jun 12, 2020 at 15:32 -
the file is moved which is a meh but as the function is expected to handle imgase from the tmp dir it is not surprising. On the bright side there is a 'pre_move_uploaded_file' filter that seems to control that Commented Apr 4, 2022 at 4:15