如何创建mshot图像的本地缓存

时间:2015-07-22 作者:Jinson Abraham

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.

<?php
    $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 个回复
SO网友:Lasse M. Tvedt

我认为这应该行得通。

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 \'\';
        else:
            $name = rand(0,100000).".jpg";
            $tmp = $tmpnew;
        endif;
    endif;

    // 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;
}
我知道这个脚本正在运行,但我会做一些更改。比如图像的命名方式。你也可以看看this.

结束

相关推荐

Featured images get shrunken

上传特色图片时,我遇到的问题是,所有图片都会自动缩小。我想保留原始图像。检查this example. 所有员工的图片都会自动缩小,但在特色图片中,我上传了员工的完整图片。我认为图像太大,wordpress会自动缩小图像,因此,我在媒体库中缩放并裁剪了图像。一些图像已修复,但一些图像仍然存在问题。有没有一种方法可以让原始上传的图像按原样显示?