media_sideload_image [ WordPress Function ]
media_sideload_image ( $file, $post_id, $desc = null )
| Parameters: |
|
| Returns: |
|
| Defined at: |
|
Similar Functions: media_upload_image, media_upload_file, media_handle_sideload, media_upload_video, wp_load_image
Download an image from the specified URL and attach it to a post.
Source
<?php
function media_sideload_image($file, $post_id, $desc = null) {
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']);
return $id;
}
$src = wp_get_attachment_url( $id );
}
// Finally check to make sure the file has been saved, then return the html
if ( ! empty($src) ) {
$alt = isset($desc) ? esc_attr($desc) : '';
$html = "<img src='$src' alt='$alt' />";
return $html;
}
}
?>
Examples [ wp-snippets.com ]
Top Google Search Results
- post thumbnails - media_sideload_image generates blank ...
Jun 9, 2011 ... Secondly, media_sideload_image won't return a WP error object if things fail. If things fail, it will return the ID of the post passed in ( $pid in your ...
wordpress.stackexchange.com - media_sideload_image (WordPress Function) - WPSeek.com
WordPress lookup for media_sideload_image, a WordPress Function. wpseek. com is a WordPress-centric search tool for developers and theme authors.
wpseek.com - WordPress › Support » media_sideload_image generates blank?
I'm creating a custom post form that is supposed to take an external image and uploads it to the media library and attach it to that post. This should be possible ...
wordpress.org - media_sideload_image((string) $movie->poster ... - Stack Overflow
Jan 3, 2012 ... But when I try to attach the movie poster to the post, the 'media_sideload_image(( string) $movie->poster, $postID);' instruction stops the loop ...
stackoverflow.com
User discussions [ wordpress.org ]
- jocken on "media_sideload_image doesn't attach image to post"
- ed4becky on "media_sideload_image generates blank?"
- flxfxp on "media_sideload_image doesn't attach image to post"
- flxfxp on "media_sideload_image doesn't attach image to post"
- flxfxp on "media_sideload_image generates blank?"
- Andy Max Jensen on "media_sideload_image dies"