I am using the Wordpress mshots api to generate automatic thumbnails of websites from the site url. I am using a customfield to capture the website url and pass the value to the mshots url to return the screenshot.

    $shot = get_post_meta($post->ID, 'website_url', true);
    $url = str_replace('http://', '', $shot);
    $imgurl = "http://s.wordpress.com/mshots/v1/".$url;
<img src="<?php echo $imurl ?>" width="300" height="200" alt="<?php the_title(); ?>" /> 

It is working fine. But I wonder how can I create a local cache of the generated screenshots in the theme folder, so that it can be displayed instead of making a remote server call every time the image is requested.

1 Answer 1


I think this should work.

function upload_image_from_url($url) {

    /** Require dependencies */
    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    require_once( ABSPATH . 'wp-admin/includes/file.php' );
    require_once( ABSPATH . 'wp-admin/includes/media.php' );     

    // Save as a temporary file
    $tmp = download_url( $url );

    // Check for download errors
    if ( is_wp_error( $tmp ) ) 
        @unlink( $file_array[ 'tmp_name' ] );
        return $tmp;

    // Image name (just random-number)
    $name = rand(0,100000).".jpg";

    // Take care of image files without extension:
    $path = pathinfo( $tmp );
    if( ! isset( $path['extension'] ) ):
        $tmpnew = $tmp . '.tmp';
        if( ! rename( $tmp, $tmpnew ) ):
            return '';
            $name = rand(0,100000).".jpg";
            $tmp = $tmpnew;

    // Upload the image into the WordPress Media Library:
    $file_array = array(
        'name'     => $name,
        'tmp_name' => $tmp
    $id = media_handle_sideload( $file_array, 0 );

    // Check for handle sideload errors:
    if ( is_wp_error( $id ) )
        @unlink( $file_array['tmp_name'] );
        return $id;

    return $id;

I know this script is working, but I would do a few changes. Like how the images are named. You can also take a look at this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.