Skip to content

Instantly share code, notes, and snippets.

@wpmark
Created July 10, 2015 10:32
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save wpmark/15e3dd1b9e6f81b83904 to your computer and use it in GitHub Desktop.
Save wpmark/15e3dd1b9e6f81b83904 to your computer and use it in GitHub Desktop.
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