Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sudarshann/bdf96f9d2d15e05629087429e59f24d3 to your computer and use it in GitHub Desktop.
Save sudarshann/bdf96f9d2d15e05629087429e59f24d3 to your computer and use it in GitHub Desktop.
Simple wordpress php class to download external images to media
class downloadGoogleDriveImage {
public static function download_external_url_by_post_id($post_id, $meta_keys){
$result = [];
foreach($meta_keys as $meta_key){
$url = trim(get_post_meta($post_id, $meta_key, true));
if(empty($url)){
$result[$meta_key] = false;
continue;
}
if(substr( $url, 0, 4 ) !== "http"){
$result[$meta_key] = false;
continue;
}
$result[$meta_key] = self::download_image($url);
}
return $result;
}
public static function export_google_url($url) {
if (strpos($url, "https://drive.google.com/file/d/") === false) {
return $url;
}
$unique_id = str_replace(array("https://drive.google.com/file/d/", "/view?usp=sharing"), array('', ''), $url);
return "https://drive.google.com/uc?export=download&id=" . $unique_id;
}
private static function get_file_name_from_disposition($header){
if (preg_match('/Content-Disposition:.*?filename="(.+?)"/', $header, $matches)) {
return $matches[1];
}
if (preg_match('/Content-Disposition:.*?filename=([^; ]+)/', $header, $matches)) {
return rawurldecode($matches[1]);
}
return false;
}
public static function download_image($url, $path = ''){
$image_url = self::export_google_url($url);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $image_url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
$res = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
curl_close($ch);
$header = substr($res, 0, $header_size);
$body = substr($res, $header_size);
$filename = self::get_file_name_from_disposition($header);
if(empty($filename)){
return false;
}
$upload_dir = "";
if(!empty($path)){
$upload_dir = $path;
} else{
$upload_dir = wp_upload_dir()['path'];
}
$file = '';
if (wp_mkdir_p($upload_dir)) {
$file = $upload_dir . '/' . $filename;
} else {
$file = $upload_dir . '/' . $filename;
}
file_put_contents($file, $body);
$wp_filetype = wp_check_filetype($filename, null);
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $file);
$attach_data = wp_generate_attachment_metadata($attach_id, $file);
wp_update_attachment_metadata($attach_id, $attach_data);
return $attach_id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment