Quantcast
Channel: WordPress › Support » Forum: Hacks - Recent Topics
Viewing all articles
Browse latest Browse all 8245

hombero on "media_handle_sideload() not working, halts execution"

$
0
0

Hello,

I am attempting to write a PHP script which downloads an off-site image from url, saves it to a permanent directory, and then attach it to a post as a thumbnail. The script successfully saves the temp file, and then saves a permanent file in the wp-content/uploads/... directory, but the call to media_handle_sideload() halts execution.

This is what I have so far:

function wp_sideload_image($post_id, $file, $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
		if ($debug) { echo 'File array: <br />';
			var_dump($file_array);
			echo 'Post id: <br />';
			echo $post_id;
			echo 'Desc: <br />';
			echo $desc;
		}
// Execution fails on next line
		$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);
	}
}

The parameters being passed are:
$post_id -> an integer representing the post to which to attach
$file -> the url to the remote file
$desc (optional) -> the description of the attachment

I have confirmed that the variables are valid when entering the function, though the script halts when media_handle_sideload() is called.

Any insight and/or help with this issue will be extremely appreciated, thank you!


Viewing all articles
Browse latest Browse all 8245

Trending Articles