Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using Media Handle Sideload
<?php
/* set the url of the file to sideload - probably be from $_POST or something */
$url = 'http://domain.com/image.jpg';
/**
* donwload the url into wordpress
* saved temporarly for now
*/
$tmp = download_url( $url );
/**
* biild an array of file information about the url
* getting the files name using basename()
*/
$file_array = array(
'name' => basename( $url ),
'tmp_name' => $tmp
);
/**
* Check for download errors
* if there are error unlink the temp file name
*/
if ( is_wp_error( $tmp ) ) {
@unlink( $file_array[ 'tmp_name' ] );
return $tmp;
}
/**
* now we can use the sideload function
* we pass it the file array of the file to handle
* and the post id of the post to attach it too
* it returns the attachment id if the file
*/
$id = media_handle_sideload( $file_array, $post_id );
/**
* check for handle sideload errors
* if errors again unlink the file
*/
if ( is_wp_error( $id ) ) {
@unlink( $file_array['tmp_name'] );
return $id;
}
/**
* get the url from the newly upload file
* $value now contians the file url in WordPress
* $id is the attachment id
*/
$value = wp_get_attachment_url( $id );
// probbaly do something here with $value (or $id)
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.