Created
May 16, 2017 10:05
-
-
Save bulini/6b8201fad1d3128b3d1afdccea1dff75 to your computer and use it in GitHub Desktop.
This file contains 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 | |
/** | |
* Insert an attachment from an URL address. | |
* | |
* @param String $url | |
* @param Int $post_id | |
* @param Array $meta_data | |
* @return Int Attachment ID | |
*/ | |
function insert_attachment_from_url($url, $post_id = null) { | |
if( !class_exists( 'WP_Http' ) ) | |
include_once( ABSPATH . WPINC . '/class-http.php' ); | |
$http = new WP_Http(); | |
$response = $http->request( $url ); | |
if( $response['response']['code'] != 200 ) { | |
return false; | |
} | |
$upload = wp_upload_bits( basename($url), null, $response['body'] ); | |
if( !empty( $upload['error'] ) ) { | |
return false; | |
} | |
$file_path = $upload['file']; | |
$file_name = basename( $file_path ); | |
$file_type = wp_check_filetype( $file_name, null ); | |
$attachment_title = sanitize_file_name( pathinfo( $file_name, PATHINFO_FILENAME ) ); | |
$wp_upload_dir = wp_upload_dir(); | |
$post_info = array( | |
'guid' => $wp_upload_dir['url'] . '/' . $file_name, | |
'post_mime_type' => $file_type['type'], | |
'post_title' => $attachment_title, | |
'post_content' => '', | |
'post_status' => 'inherit', | |
); | |
// Create the attachment | |
$attach_id = wp_insert_attachment( $post_info, $file_path, $post_id ); | |
// Include image.php | |
require_once( ABSPATH . 'wp-admin/includes/image.php' ); | |
// Define attachment metadata | |
$attach_data = wp_generate_attachment_metadata( $attach_id, $file_path ); | |
// Assign metadata to attachment | |
wp_update_attachment_metadata( $attach_id, $attach_data ); | |
return $attach_id; | |
} | |
if($_GET['upload']): | |
$url = $_GET['scraped_url']; | |
$string = file_get_contents($url); | |
$dom = new domDocument; | |
/*** load the html into the object ***/ | |
$dom->loadHTML($string); | |
/*** discard white space ***/ | |
$dom->preserveWhiteSpace = false; | |
$images = $dom->getElementsByTagName('img'); | |
foreach($images as $img) | |
{ | |
$url = $img->getAttribute('src'); | |
$alt = $img->getAttribute('alt'); | |
//echo "Title: $alt<br>$url<br>"; | |
insert_attachment_from_url($url,get_the_ID()); | |
echo $url.'<br />'; | |
} exit(); | |
endif; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment