Last active
May 2, 2018 03:12
-
-
Save trangsihung/3cc93b2b5c52cf15b45821805eff09ea to your computer and use it in GitHub Desktop.
WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment