完整可以的WordPress文章远程(外链)图片自动保存本地化(亲测可用哦)

有些时候我们在写文章的时候,难免可能要用到别人的图片,或者说转载文章,就要用到了复制文章,但是里面的老是别人的,总归不好,有一天别人站打不开,在想查看文章的时候,图片就全是XXX的,感觉会很不爽,如何才能让让WordPress远程文章中图片本地化呢?方法固然有,插件不少,还是秉着少用一个插件略微安全的原则,还是使用代码比较好,具体呢请看;

百度了一下,网上都是很多的ctrl+c然后加V,复制粘贴类型,也都不测试,根本就是不能用的代码;比如(网上都是这个109行代码的保存):

//自动本地化外链图片
add_filter('content_save_pre', 'auto_save_image');
function auto_save_image($content) {
$upload_path = '';
$upload_url_path = get_bloginfo('url');
//上传目录
if (($var = get_option('upload_path')) !=''){
$upload_path = $var;
} else {
$upload_path = 'wp-content/uploads';
}
if(get_option('uploads_use_yearmonth_folders')) {
$upload_path .= '/'.date("Y",time()).'/'.date("m",time());
}
//文件地址
if(($var = get_option('upload_url_path')) != '') {
$upload_url_path = $var;
} else {
$upload_url_path = bloginfo('url');
}
if(get_option('uploads_use_yearmonth_folders')) {
$upload_url_path .= '/'.date("Y",time()).'/'.date("m",time());
}
require_once ("../wp-includes/class-snoopy.php");
$snoopy_Auto_Save_Image = new Snoopy;
$img = array();
//以文章的标题作为图片的标题
if ( !emptyempty( $_REQUEST['post_title'] ) )
$post_title = wp_specialchars( stripslashes( $_REQUEST['post_title'] ));
$text = stripslashes($content);
if (get_magic_quotes_gpc()) $text = stripslashes($text);
preg_match_all("/ src=(\"|\'){0,}(http:\/\/(.+?))(\"|\'|\s)/is",$text,$img);
$img = array_unique(dhtmlspecialchars($img[2]));
foreach ($img as $key => $value){
set_time_limit(180); //每个图片最长允许下载时间,秒
if(str_replace(get_bloginfo('url'),"",$value)==$value&&str_replace(get_bloginfo('home'),"",$value)==$value){
//判断是否是本地图片,如果不是,则保存到服务器
$fileext = substr(strrchr($value,'.'),1);
$fileext = strtolower($fileext);
if($fileext==""||strlen($fileext)>4)
$fileext = "jpg";
$savefiletype = array('jpg','gif','png','bmp');
if (in_array($fileext, $savefiletype)){
if($snoopy_Auto_Save_Image->fetch($value)){
$get_file = $snoopy_Auto_Save_Image->results;
}else{
echo "error fetching file: ".$snoopy_Auto_Save_Image->error."<br>";
echo "error url: ".$value;
die();
}
$filetime = time();
$filepath = "/".$upload_path;//图片保存的路径目录
!is_dir("..".$filepath) ? mkdirs("..".$filepath) : null;
//$filename = date("His",$filetime).random(3);
$filename = substr($value,strrpos($value,'/'),strrpos($value,'.')-strrpos($value,'/'));
//$e = '../'.$filepath.$filename.'.'.$fileext;
//if(!is_file($e)) {
// copy(htmlspecialchars_decode($value),$e);
//}
$fp = @fopen("..".$filepath.$filename.".".$fileext,"w");
@fwrite($fp,$get_file);
fclose($fp);
$wp_filetype = wp_check_filetype( $filename.".".$fileext, false );
$type = $wp_filetype['type'];
$post_id = (int)$_POST['temp_ID2'];
$title = $post_title;
$url = $upload_url_path.$filename.".".$fileext;
$file = $_SERVER['DOCUMENT_ROOT'].$filepath.$filename.".".$fileext;
//添加数据库记录
$attachment = array(
'post_type' => 'attachment',
'post_mime_type' => $type,
'guid' => $url,
'post_parent' => $post_id,
'post_title' => $title,
'post_content' => '',
);
$id = wp_insert_attachment($attachment, $file, $post_parent);
$text = str_replace($value,$url,$text); //替换文章里面的图片地址
}
}
}
$content = AddSlashes($text);
remove_filter('content_save_pre', 'auto_save_image');
return $content;
}
function mkdirs($dir)
{
if(!is_dir($dir))
{
mkdirs(dirname($dir));
mkdir($dir);
}
return ;
}
function dhtmlspecialchars($string) {
if(is_array($string)) {
foreach($string as $key => $val) {
$string[$key] = dhtmlspecialchars($val);
}
}else{
$string = str_replace('&', '&', $string);
$string = str_replace('"', '"', $string);
$string = str_replace('<', '<', $string);
$string = str_replace('>', '>', $string);
$string = preg_replace('/&(#\d;)/', '&\1', $string);
}
return $string;
}

我也是用了此代码,然后看我使用的效果;远程图片可以正常下载在,但是在显示文章会出现路径不正确;是不是,这就很尴尬了,那就自己动手丰衣足食,那我们就来操作一下吧;

修改后的代码(非常滴可用):

//自动本地化外链图片
add_filter('content_save_pre', 'auto_save_image');
function auto_save_image($content) {
$upload_path = '';
$upload_url_path = get_bloginfo('url');
//上传目录
if (($var = get_option('upload_path')) != '') {
$upload_path = $var;
} else {
$upload_path = 'wp-content/uploads';
}
if (get_option('uploads_use_yearmonth_folders')) {
$upload_path.= '/' . date("Y", time()) . '/' . date("m", time());
}
//文件地址
if (($var = get_option('upload_url_path')) != '') {
$upload_url_path = $var;
} else {
$upload_url_path = get_bloginfo('url');
}
if (get_option('uploads_use_yearmonth_folders')) {
$upload_url_path.= '/wp-content/uploads/' . date("Y", time()) . '/' . date("m", time());
}
require_once ("../wp-includes/class-snoopy.php");
$snoopy_Auto_Save_Image = new Snoopy;
$img = array();
//以文章的标题作为图片的标题
if (!empty($_REQUEST['post_title'])) $post_title = wp_specialchars(stripslashes($_REQUEST['post_title']));
$text = stripslashes($content);
if (get_magic_quotes_gpc()) $text = stripslashes($text);
preg_match_all("/ src=(\"|\'){0,}(http:\/\/(.+?))(\"|\'|\s)/is", $text, $img);
$img = array_unique(dhtmlspecialchars($img[2]));
foreach ($img as $key => $value) {
set_time_limit(180); //每个图片最长允许下载时间,秒
if (str_replace(get_bloginfo('url'), "", $value) == $value && str_replace(get_bloginfo('home'), "", $value) == $value) {
//判断是否是本地图片,如果不是,则保存到服务器
$fileext = substr(strrchr($value, '.'), 1);
$fileext = strtolower($fileext);
if ($fileext == "" || strlen($fileext) > 4) $fileext = "jpg";
$savefiletype = array('jpg', 'gif', 'png', 'bmp');
if (in_array($fileext, $savefiletype)) {
if ($snoopy_Auto_Save_Image->fetch($value)) {
$get_file = $snoopy_Auto_Save_Image->results;
} else {
echo "error fetching file: " . $snoopy_Auto_Save_Image->error . "<br>";
echo "error url: " . $value;
die();
}
$filetime = time();
$filepath = "/" . $upload_path; //图片保存的路径目录
!is_dir(".." . $filepath) ? mkdirs(".." . $filepath) : null;
//$filename = date("His",$filetime).random(3);
$filename = substr($value, strrpos($value, '/'), strrpos($value, '.') - strrpos($value, '/'));
//$e = '../'.$filepath.$filename.'.'.$fileext;
//if(!is_file($e)) {
// copy(htmlspecialchars_decode($value),$e);
//}
$fp = @fopen(".." . $filepath . $filename . "." . $fileext, "w");
@fwrite($fp, $get_file);
fclose($fp);
$wp_filetype = wp_check_filetype($filename . "." . $fileext, false);
$type = $wp_filetype['type'];
$post_id = (int)$_POST['temp_ID2'];
$title = $post_title;
$url = $upload_url_path . $filename . "." . $fileext;
$file = $_SERVER['DOCUMENT_ROOT'] . $filepath . $filename . "." . $fileext;
//添加数据库记录
$attachment = array('post_type' => 'attachment', 'post_mime_type' => $type, 'guid' => $url, 'post_parent' => $post_id, 'post_title' => $title, 'post_content' => '',);
$id = wp_insert_attachment($attachment, $file, $post_parent);
$text = str_replace($value, $url, $text); //替换文章里面的图片地址

}
}
}
$content = AddSlashes($text);
remove_filter('content_save_pre', 'auto_save_image');
return $content;
}
function mkdirs($dir) {
if (!is_dir($dir)) {
mkdirs(dirname($dir));
mkdir($dir);
}
return;
}
function dhtmlspecialchars($string) {
if (is_array($string)) {
foreach ($string as $key => $val) {
$string[$key] = dhtmlspecialchars($val);
}
} else {
$string = str_replace('&', '&', $string);
$string = str_replace('"', '"', $string);
$string = str_replace('<', '<', $string);
$string = str_replace('>', '>', $string);
$string = preg_replace('/&(#\d;)/', '&\1', $string);
}
return $string;
}

PS:切记,我们网站上复制的代码都是GBK,请使用的时候转换成U8再使用哦,切记哦,不然会导致网站挂掉的哦~~~具体请看下面的链接即可;

复制的PHP文件运行打开是乱码如何解决?(PHP GBK编码变UTF-8)

所写所说,是心之所感,思之所悟,行之所得;文当无敷衍,落笔求简洁。 以所舍,求所获;有所依,方所成!

更多请关注:老梁`s Blog

免责声明,若由于商用引起版权纠纷,一切责任均由使用者承担。 您必须遵守我们的协议,如果您下载了该资源行为将被视为对《免责声明》全部内容的认可->联系老梁投诉资源
Laoliang.Net资源全部来自互联网收集,仅供用于学习和交流,请勿用于商业用途。如有侵权、不妥之处,请联系站长并出示版权证明以便删除。 敬请谅解! 侵权删帖/违法举报/投稿等事物联系邮箱:service@laoliang.net
老梁`s Blog(老梁博客) » 完整可以的WordPress文章远程(外链)图片自动保存本地化(亲测可用哦)

1 评论

  1. 感谢分享,谢谢站长!!

发表评论

本站承接,网站推广(SEM,SEO),软件的安装的安装与调试,服务器的推荐以及配置,APP的开发与维护,网络或者web维护;财务软件,客户管理系统,人力资源,超市POS,医药管理,服务器安全,ecshop,金蝶,用友,管家婆;

立即查看 了解详情