Skip to content

Instantly share code, notes, and snippets.

@marteinn
Last active December 20, 2015 18:09
Show Gist options
  • Select an option

  • Save marteinn/6174127 to your computer and use it in GitHub Desktop.

Select an option

Save marteinn/6174127 to your computer and use it in GitHub Desktop.
Example on how to download, save and insert image as a attachment to Wordpress from a web url.
<?php
/**
* Create image attachment using a web url.
*
* @param String url Url path to the image we want to add (http://test.com/img.jpg)
* @param String filename Name of file ex: image.jpg. Will otherwise be loaded by header.
* @param int post_id The post where image should be associated if featured
* is true. (Optiona)
* @param Boolean featured Whether a file should be featured or not. (Optional)
* @return int Id for the created attachment.
*/
function save_image($url, $filename = NULL, $post_id = 0, $featured = false) {
// Read file
if ($filename == NULL) {
// Loop through headers and and find filename.
$headers = get_headers($url);
foreach ($headers as $header_key => $header_data) {
$matches = array();
$result = preg_match("/filename=\"(.*)\"$/i", $header_data,
$matches);
if (count($matches[1])) {
$filename = $matches[1];
}
}
// If no filename is found, use basename
if ($filename == NULL) {
$filename = basename($url);
}
}
$filename = sanitize_file_name($filename);
// Load file content
$data = file_get_contents($url);
if ($data == false) {
return 0;
}
// Save file to disk
$upload_dir = array(
"path" => "./",
"url" => ""
);
$save_path = $upload_dir["path"]."/".$filename;
$save_url = $upload_dir["url"].$filename;
$response = file_put_contents($save_path, $data);
// Add attachment
$filetype = wp_check_filetype($save_path, null );
$attachment = array(
"guid" => $save_url,
"post_mime_type" => $filetype["type"],
"post_title" => $filename,
"post_content" => "",
"post_status" => "inherit"
);
$attachment_id = wp_insert_attachment($attachment, $save_path, 0);
// Generate metadata
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata($attachment_id,
$save_path);
$metadata = wp_update_attachment_metadata($attachment_id,
$attachment_data);
// Add as a featured image
if ($featured && $metadata) {
update_post_meta($post_id, '_thumbnail_id', $attachment_id);
}
return $attachment_id;
}
save_image("http://yourfileurl.com/image.jpg");
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment