Skip to content

Instantly share code, notes, and snippets.

@kyle-jennings
Created January 11, 2019 16:26
Show Gist options
  • Save kyle-jennings/2823a2cc4c1e89cc64e8b5241ef55bb4 to your computer and use it in GitHub Desktop.
Save kyle-jennings/2823a2cc4c1e89cc64e8b5241ef55bb4 to your computer and use it in GitHub Desktop.
Programmatically upload file to WordPress
// downloads a file from a URL and saves it to the /tmp folder in the OS
$tmp_file = download_url( $url );
// the file info
$file = array(
'name' => $filename_with_extension,
'type' => 'image/png',
'tmp_name' => $tmp_file, //src file
'error' => 0,
'size' => filesize( $tmp_file ),
);
// get the ID of the uploaded file
$id = wp_handle_sideload( $file, 0); // the file info, and the post to attach it to
if ( is_wp_error($id) ) {
return false;
}
wp_update_attachment_metadata($id);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment