First, Here is the full error:
PHP Fatal error: Call to undefined function download_url() in /path/to/wordpress/wp-admin/includes/media.php on line 562
I have also posted the related functions at the bottom of my question.
I am modifying a script for my company’s website which allows us to automate the retrieval and uploading of content from our content provider. Due to the way they organize their XML, I need to upload the images related to the articles separately from the main body of the articles. I tried using media_sideload_image() to do this, but I recieved the error:
The function (media_sideload_image()) which calls download_url and results in the error:
PHP Fatal error: Call to undefined function download_url() in /path/to/wordpress/wp-admin/includes/media.php on line 562
As can be seen, I successfully included media.php – and the rest of my script has already been implemented on to the site, and I have not run into any other issues with accessing WordPress files. The error would appear to be with media.php itself – which I find unusual.
Any ideas on how I can resolve this problem? Alternatively, if you know of another function I can use to do this, that would also be appreciated.
By all means, if you require any more details on the issue just ask.
/**
* Download an image from the specified URL and attach it to a post.
*
* @since 2.6.0
*
* @param string $file The URL of the image to download
* @param int $post_id The post ID the media is to be associated with
* @param string $desc Optional. Description of the image
* @return string|WP_Error Populated HTML img tag on success
*/
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="https://wordpress.stackexchange.com/questions/17805/$src" alt="$alt" />";
return $html;
}
}
The function where I call media_sideload_image() in my code:
//Upload the image if it exists, and return the post_id
function upload_image($post_id, $image_url) {
require_once('wp-admin/includes/media.php');
$image_url="http://admin.gkbusiness.com/gkbusiness/files/2011/04/LOGOGKMBUS1.jpg";
media_sideload_image($image_url, $post_id);
return $post_id;
}