Definition:
function media_handle_sideload($file_array, $post_id, $desc = null, $post_data = array() {}
This handles a sideloaded file in the same way as an uploaded file is handled by media_handle_upload()
Parameters
- array $file_array: Array similar to a $_FILES upload array
- int $post_id: The post ID the media is associated with
- string $desc: Description of the sideloaded file
- array $post_data: allows you to overwrite some of the attachment
Return values
returns:ID of the attachment or a WP_Error on failure
Source code
function media_handle_sideload($file_array, $post_id, $desc = null, $post_data = array()) { $overrides = array('test_form'=>false); $file = wp_handle_sideload($file_array, $overrides); if ( isset($file['error']) ) return new WP_Error( 'upload_error', $file['error'] ); $url = $file['url']; $type = $file['type']; $file = $file['file']; $title = preg_replace('/\.[^.]+$/', '', basename($file)); $content = ''; // use image exif/iptc data for title and caption defaults if possible if ( $image_meta = @wp_read_image_metadata($file) ) { if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) $title = $image_meta['title']; if ( trim( $image_meta['caption'] ) ) $content = $image_meta['caption']; } $title = isset($desc) ? $desc : ''; // Construct the attachment array $attachment = array_merge( array( 'post_mime_type' => $type, 'guid' => $url, 'post_parent' => $post_id, 'post_title' => $title, 'post_content' => $content, ), $post_data ); // This should never be set as it would then overwrite an existing attachment. if ( isset( $attachment['ID'] ) ) unset( $attachment['ID'] ); // Save the attachment metadata $id = wp_insert_attachment($attachment, $file, $post_id); if ( !is_wp_error($id) ) wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) ); return $id; }
2349
function attach_image_url($file, $post_id, $desc = null) {
require_once(ABSPATH . “wp-admin” . ‘/includes/image.php’);
require_once(ABSPATH . “wp-admin” . ‘/includes/file.php’);
require_once(ABSPATH . “wp-admin” . ‘/includes/media.php’);
if ( ! empty($file) ) {
// Download file to temp location
$tmp = download_url( $file );
// Set variables for storage
// fix file filename for query strings
preg_match(‘/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/’, $file, $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’]);}
add_post_meta($post_id, ‘_thumbnail_id’, $id, true);
}
}