5

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 1

4

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 );
2
  • 1
    Important 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

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.