不用任何插件实现wordpress自动保存远程图片

我很喜欢Ctrl+C+Ctrl+V,有时候粘贴到文章上的图片是链接别人网站的图片,方便是方便,可万一别人做了防盗链或是换地址,你这边就瞎白活了。于是就想下个插件,可是这功能也很简单,为了不增加负担,于是就把插件代码收集下来放到主题functions.php文件中,那么所有的图片地址非本站的都会自动下载并保存到你在“媒体选项”所设置的“上传文件”里的文件夹和地址里,因为空间有限制所以生成缩略图我就没有用和测试,代码是有的如果有什么问题留言吧,不费话了上代码~

/*
Plugin Name: DX-auto-save-images
Plugin URI: http://www.daxiawp.com/dx-auto-save-images.html
Description: Automatically keep the remote picture to the local, and automatically generate thumbnails. 自动保持远程图片到本地,并且自动生成缩略图。
Version: 1.4.0
Author: 大侠wp
Author URI: http://www.daxiawp.com/dx-auto-save-images.html
Copyright: daxiawp开发的原创插件,任何个人或团体不可擅自更改版权。
*/

//save post exterior images

function wpsi_post_save_images( $content ){
if( ($_POST['save'] || $_POST['publish']) && ($_POST['DS_switch']!='not_save') ){
set_time_limit(240);
global $post;
$post_id=$post->ID;
$preg=preg_match_all('/<img.*?src="(.*?)"/',stripslashes($content),$matches);
if($preg){
$i = 1;
foreach($matches[1] as $image_url){
if(empty($image_url)) continue;
$pos=strpos($image_url,get_bloginfo('url'));
if($pos===false){
$res=wpsi_save_images($image_url,$post_id,$i);
$replace=$res['url'];
$content=str_replace($image_url,$replace,$content);
}
$i++;
}
}
}

remove_filter( 'content_save_pre','wpsi_post_save_images');
return $content;
}

//save exterior images

function wpsi_save_images($image_url,$post_id,$i){
$file=file_get_contents($image_url);
$filename=basename($image_url);
preg_match( '/(.*?)(\.\w+)$/', $filename, $match );
$im_name = date("YmdHis").floor(microtime()*1000).$match[2];
$res=wp_upload_bits($im_name,'',$file);
/*====这个是生成缩略图不需要就删除或注释掉开始=====*/
$attach_id = wpsi_insert_attachment($res['file'],$post_id);
if( $options['post-tmb']=='yes' && $i==1 ){
set_post_thumbnail( $post_id, $attach_id );
}
/*====这个是生成缩略图不需要就删除或注释掉结束====*/
return $res;
}

/*====这个是生成缩略图不需要就删除或注释掉开始=====*/
//insert attachment
function wpsi_insert_attachment($file,$id){
$dirs=wp_upload_dir();
$filetype=wp_check_filetype($file);
$attachment=array(
'guid'=>$dirs['baseurl'].'/'._wp_relative_upload_path($file),
'post_mime_type'=>$filetype['type'],
'post_title'=>preg_replace('/\.[^.]+$/','',basename($file)),
'post_content'=>'',
'post_status'=>'inherit'
);

$attach_id=wpsi_insert_attachment($attachment,$file,$id);
$attach_data=wp_generate_attachment_metadata($attach_id,$file);
wp_update_attachment_metadata($attach_id,$attach_data);
return $attach_id;
}
/*====这个是生成缩略图不需要就删除或注释掉结束====*/

add_filter( 'content_save_pre','wpsi_post_save_images');


代码来源于:DX-auto-save-images插件,不会动手的朋友还是去后台-插件-安装插件,搜索"DX-auto-save-images",直接在wordpress后台安装。

如果您觉得我的文章有帮助,请随意赞赏!

此处评论已关闭