media_sideload_image

Downloads an image from the specified URL and attaches it to a post.

Description

(string|WP_Error) media_sideload_image( (string) $file, (int) $post_id, (constant) $desc = null, (string) $return = 'html' ); 

Returns (string|WP_Error)

Populated HTML img tag on success, WP_Error object otherwise.

Parameters (4)

0. $file (string)
The URL of the image to download.
1. $post_id (int)
The post ID the media is to be associated with.
2. $desc — Optional. (constant) => null
Description of the image.
3. $return — Optional. (string) => 'html'
Accepts html (image tag html) or src. (URL). Default html .

Usage

  1. if ( !function_exists( 'media_sideload_image' ) ) { 
  2. require_once ABSPATH . '/wp-admin/includes/media.php'; 
  3.  
  4. // The URL of the image to download. 
  5. $file = ''; 
  6.  
  7. // The post ID the media is to be associated with. 
  8. $post_id = -1; 
  9.  
  10. // Optional. Description of the image. 
  11. $desc = null; 
  12.  
  13. // Optional. Accepts 'html' (image tag html) or 'src' (URL). Default 'html'. 
  14. $return = 'html'; 
  15.  
  16. // NOTICE! Understand what this does before running. 
  17. $result = media_sideload_image($file, $post_id, $desc, $return); 
  18.  

Defined (1)

The function is defined in the following location(s).

/wp-admin/includes/media.php  
  1. function media_sideload_image( $file, $post_id, $desc = null, $return = 'html' ) { 
  2. if ( ! empty( $file ) ) { 
  3.  
  4. // Set variables for storage, fix file filename for query strings. 
  5. preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches ); 
  6. if ( ! $matches ) { 
  7. return new WP_Error( 'image_sideload_failed', __( 'Invalid image URL' ) ); 
  8.  
  9. $file_array = array(); 
  10. $file_array['name'] = basename( $matches[0] ); 
  11.  
  12. // Download file to temp location. 
  13. $file_array['tmp_name'] = download_url( $file ); 
  14.  
  15. // Iferrorstoring temporarily, return the error. 
  16. if ( is_wp_error( $file_array['tmp_name'] ) ) { 
  17. return $file_array['tmp_name']; 
  18.  
  19. // Do the validation and storage stuff. 
  20. $id = media_handle_sideload( $file_array, $post_id, $desc ); 
  21.  
  22. // Iferrorstoring permanently, unlink. 
  23. if ( is_wp_error( $id ) ) { 
  24. @unlink( $file_array['tmp_name'] ); 
  25. return $id; 
  26.  
  27. $src = wp_get_attachment_url( $id ); 
  28.  
  29. // Finally, check to make sure the file has been saved, then return the HTML. 
  30. if ( ! empty( $src ) ) { 
  31. if ( $return === 'src' ) { 
  32. return $src; 
  33.  
  34. $alt = isset( $desc ) ? esc_attr( $desc ) : ''; 
  35. $html = "<img src='$src' alt='$alt' />"; 
  36. return $html; 
  37. } else { 
  38. return new WP_Error( 'image_sideload_failed' );