Download external images if post is publish

I have scheduled posts that contain external images. I want it to automatically download images & linked to the media library if the post status is publish. Now the problem is my code won’t download images when the schedule post becomes published. It works if you create the post and publish straight away but not for a schedule post that later converts to publish.

Can anyone help me fix the code?

<?php  
/*  
Plugin Name: Download External images
Version: 1.0
*/
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);   

    $first_image="";

    if(preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches)){
        $first_image = $matches [1] [0];
    }

    if (strpos($first_image,$_SERVER['HTTP_HOST'])===false)
    {

        //Fetch and Store the Image 
        $get = wp_remote_get( $first_image );
        $type = wp_remote_retrieve_header( $get, 'content-type' );
        $mirror = wp_upload_bits(rawurldecode(basename( $first_image )), '', wp_remote_retrieve_body( $get ) );

        //Attachment options
        $attachment = array(
        'post_title'=> basename( $first_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, $first_image );
        wp_update_attachment_metadata( $attach_id, $attach_data );
        set_post_thumbnail( $post_ID, $attach_id );

        $updated = str_replace($first_image, $mirror['url'], $post->post_content);

        //Replace the image in the post
        wp_update_post(array('ID' => $post_ID, 'post_content' => $updated));

        // re-hook this function
        add_action('publish_post', 'fetch_images');     
    }
}
?>

1 Answer
1

Scheduled posts don’t trigger publish_post, only updating the post itself will do that.

Add an action for future_to_publish, see the reference on post status transitions. I don’t believe that you’ll have access to the user-object in that case, so you might want to refactor that.

Alternatively, just get the images when the user saves the post, not when it gets published. Use the save_post action.

Leave a Comment