media_handle_upload for local files?

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
1

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 );

Leave a Comment