Created
February 19, 2014 15:19
-
-
Save lucaspiller/9094117 to your computer and use it in GitHub Desktop.
Auto Save Remote Images WP Plugin
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 | |
/* | |
Plugin Name: Auto Save Remote Image | |
Plugin URI: http://www.devsaab.com/wordpress/ | |
Description: This plugin automatically downloads the first remote image from a post and sets it as the featured image. | |
Version: 1.3 | |
Author: Prebhdev Singh | |
Disclaimer: No warranty or guarantee of any kind! Use this in your own risk. | |
*/ | |
add_action('publish_post', 'fetch_images'); | |
function fetch_images( $post_ID ) | |
{ | |
//Check to make sure function is not executed more than once on save | |
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) | |
return; | |
if ( !current_user_can('edit_post', $post_ID) ) | |
return; | |
remove_action('publish_post', 'fetch_images'); | |
$post = get_post($post_ID); | |
$image = ''; | |
if(preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches)){ | |
foreach($matches[1] as $image) { | |
print($image); | |
if (strpos($image,$_SERVER['HTTP_HOST'])===false) | |
{ | |
preg_match_all('/([0-9]{4}\/[0-9]{2})\//i', $image, $matches); | |
$date = $matches [1] [0]; | |
//Fetch and Store the Image | |
$get = wp_remote_head( $image ); | |
$type = wp_remote_retrieve_header( $get, 'content-type' ); | |
$mirror = wp_upload_bits(rawurldecode(basename( $image )), '', '', $date); | |
//Attachment options | |
$attachment = array( | |
'post_title'=> basename( $image ), | |
'post_mime_type' => $type | |
); | |
// Add the image to your media library and set as featured image | |
$attach_id = wp_insert_attachment( $attachment, $mirror['file'], $post_ID ); | |
$attach_data = wp_generate_attachment_metadata( $attach_id, $image ); | |
wp_update_attachment_metadata( $attach_id, $attach_data ); | |
set_post_thumbnail( $post_ID, $attach_id ); | |
$post->post_content = str_replace($image, $mirror['url'], $post->post_content); | |
} | |
} | |
} | |
//Replace the image in the post | |
wp_update_post(array('ID' => $post_ID, 'post_content' => $post->post_content)); | |
// re-hook this function | |
add_action('publish_post', 'fetch_images'); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment