Function to Download External Images to My Site

Here is a solution to upload a copy of the image saved as a URL in a custom field into a local directory on your site. This will not add the image to the media library and is meant as more of a caching mechanism.

You should always be sure that you have permission to use images from other sources before you use them. Only use this code for good!

function downloadcouv( $post_id, $post, $update ) {

    // Update the post's metadata.

    if ( isset( $_POST['couv'] ) ) {

        // Get the upload directory
        $upload_dir = wp_upload_dir();

        // Make sure that the image URL is actually a URL
        if ( FALSE !== filter_var($_POST['couv'], FILTER_VALIDATE_URL) ) {

            // Get the file extension
            $ext = pathinfo($_POST['couv'], PATHINFO_EXTENSION);

            // Copy the file from the url to a local directory
            copy( $backdrop, $upload_dir['basedir'] . '/site-img-' . $post_id . '.' . $ext );

            // Update the post meta with the URL to the uploaded image
            update_post_meta( $post_id, 'couv2', $upload_dir['basedir'] . '/site-img-' . $post_id . '.' . $ext );

        }

    }

}
add_action( 'save_post', 'downloadcouv', 10, 3 );