Languages: English • 日本語 (Add your language)
Handles a sideloaded file in the same way as an uploaded file is handled by media_handle_upload().
(from the media_handle_upload() function)
<?php
// Need to require these files
if ( !function_exists('media_handle_upload') ) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
$url = "http://s.wordpress.org/style/images/wp3-logo.png";
$tmp = download_url( $url );
if( is_wp_error( $tmp ) ){
// download failed, handle error
}
$post_id = 1;
$desc = "The WordPress Logo";
$file_array = array();
// Set variables for storage
// fix file filename for query strings
preg_match('/[^\?]+\.(jpg|jpe|jpeg|gif|png)/i', $url, $matches);
$file_array['name'] = basename($matches[0]);
$file_array['tmp_name'] = $tmp;
// If error storing temporarily, unlink
if ( is_wp_error( $tmp ) ) {
@unlink($file_array['tmp_name']);
$file_array['tmp_name'] = '';
}
// do the validation and storage stuff
$id = media_handle_sideload( $file_array, $post_id, $desc );
// If error storing permanently, unlink
if ( is_wp_error($id) ) {
@unlink($file_array['tmp_name']);
return $id;
}
$src = wp_get_attachment_url( $id );
?>
Since: 2.6.0
media_sideload_image() is located in wp-admin/includes/media.php.
Upload Functions: media_handle_upload(), media_handle_sideload(), wp_handle_upload(), wp_import_handle_upload(), wp_handle_sideload(), media_sideload_image()
Attachment Functions:
get_children(), get attached media(), the_attachment_link(), get_attachment_link(), wp_get_attachment_link(), wp_get_attachment_image(), wp_get_attachment_image_src(), wp_get_attachment_url(), wp_get_attachment_thumb_file(), wp_get_attachment_thumb_url(), is_attachment(), wp_get_attachment_metadata()