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.
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.