WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/media handle sideload

Description

Handles a sideloaded file in the same way as an uploaded file is handled by media_handle_upload().

Parameters

$file_array
(array) (required) Array similar to a $_FILES upload array.
Default: None
$post_id
(int) (required) The post ID the media is associated with. Required, but can be set to 0, creating a media item that has no relationship to a post.
Default: None
$desc
(string) (optional) Description of the sideloaded file.
Default: null
$post_data
(array) (optional) Allows you to overwrite some of the attachment.
Default: null

Return Value

(int|object)
The ID of the attachment or a WP_Error on failure.

Examples

(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 );
?>

Change Log

Since: 2.6.0

Source File

media_sideload_image() is located in wp-admin/includes/media.php.

Resources

Related

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()

See also index of Function Reference and index of Template Tags.