Created
January 11, 2019 16:26
-
-
Save kyle-jennings/2823a2cc4c1e89cc64e8b5241ef55bb4 to your computer and use it in GitHub Desktop.
Programmatically upload file to WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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