WordPress
<?php
// Upload image from url
// Returns an array (attachment_id, url), or false
function media_import_from_url( $url ) {
$filename = basename($url);
global $wpdb;
$query = "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_value LIKE '%/$filename'";
$count = intval($wpdb->get_var($query));
if ( $count != 0 ) {
return array(
'attachment_id' => $count,
'url' => wp_get_attachment_image_url( $count, 'full' )
);
}
$upload_file = wp_upload_bits($filename, null, file_get_contents($url)); // use url_get_contents cURL if file_get_contents() false
if (!$upload_file['error']) {
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'] );
if (!is_wp_error($attachment_id)) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
return array(
'attachment_id' => $attachment_id,
'url' => $upload_file['url']
);
}
}
return false;
}
function url_get_contents ($Url) {
if (!function_exists('curl_init')){
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}