完整可以的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)
2023年1月1日更新一次:
function ecp_save_post($post_id, $post) {
global $wpdb;
if($post->post_status == 'publish') {
$p = '/<img.*[\s]src=[\"|\'](.*)[\"|\'].*>/iU';
$num = preg_match_all($p, $post->post_content, $matches);
if ($num) {
$wp_upload_dir = wp_upload_dir();
set_time_limit(0);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS,20);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
$ecp_options = $_SERVER['HTTP_HOST'];
foreach ($matches[1] as $src) {
if (isset($src) && strpos($src, $ecp_options) === false) {
$file_info = wp_check_filetype(basename($src), null);
if ($file_info['ext'] == false) {
date_default_timezone_set('PRC');
$file_name = date('YmdHis-').dechex(mt_rand(100000, 999999)).'.tmp';
} else {
$file_name = dechex(mt_rand(100000, 999999)) . '-' . basename($src);
}
curl_setopt($ch, CURLOPT_URL, $src);
$file_path = $wp_upload_dir['path'] . '/' . $file_name;
$img = fopen($file_path, 'wb');
curl_setopt($ch, CURLOPT_FILE, $img);
$img_data = curl_exec($ch);
fclose($img);
if (file_exists($file_path) && filesize($file_path) > 0) {
$t = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$arr = explode('/', $t);
if (pathinfo($file_path, PATHINFO_EXTENSION) == 'tmp') {
$file_path = ecp_handle_ext($file_path, $arr[1], $wp_upload_dir['path'], $file_name, 'tmp');
} elseif (pathinfo($file_path, PATHINFO_EXTENSION) == 'webp') {
$file_path = ecp_handle_ext($file_path, $arr[1], $wp_upload_dir['path'], $file_name, 'webp');
}
$post->post_content = str_replace($src, $wp_upload_dir['url'] . '/' . basename($file_path), $post->post_content);
$attachment = ecp_get_attachment_post(basename($file_path), $wp_upload_dir['url'] . '/' . basename($file_path));
$attach_id = wp_insert_attachment($attachment, ltrim($wp_upload_dir['subdir'] . '/' . basename($file_path), '/'), 0);
$attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
$ss = wp_update_attachment_metadata($attach_id, $attach_data);
}
}
}
curl_close($ch);
$wpdb->update( $wpdb->posts, array('post_content' => $post->post_content), array('ID' => $post->ID));
}
}
}
function ecp_handle_ext($file, $type, $file_dir, $file_name, $ext) {
switch ($ext) {
case 'tmp':
if (rename($file, str_replace('tmp', $type, $file))) {
if ('webp' == $type) {
return ecp_image_convert('webp', 'jpeg', $file_dir . '/' . str_replace('tmp', $type, $file_name));
}
return $file_dir . '/' . str_replace('tmp', $type, $file_name);
}
case 'webp':
if ('webp' == $type) {
return ecp_image_convert('webp', 'jpeg', $file);
} else {
if (rename($file, str_replace('webp', $type, $file))) {
return $file_dir . '/' . str_replace('webp', $type, $file_name);
}
}
default:
return $file;
}
}
function ecp_image_convert($from='webp', $to='jpeg', $image) {
$im = imagecreatefromwebp($image);
if (imagejpeg($im, str_replace('webp', 'jpeg', $image), 100)) {
try {
unlink($image);
} catch (Exception $e) {
$error_msg = sprintf('Error removing local file %s: %s', $image,
$e->getMessage());
error_log($error_msg);
}
}
imagedestroy($im);
return str_replace('webp', 'jpeg', $image);
}
function ecp_get_attachment_post($filename, $url) {
$file_info = wp_check_filetype($filename, null);
return array(
'guid' => $url,
'post_type' => 'attachement',
'post_mime_type' => $file_info['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit'
);
}
add_action('save_post', 'ecp_save_post', 120, 2);
问题未解决?付费解决问题加Q或微信 2589053300 (即Q号又微信号)右上方扫一扫可加博主微信
所写所说,是心之所感,思之所悟,行之所得;文当无敷衍,落笔求简洁。 以所舍,求所获;有所依,方所成!
赏
支付宝赞助
微信赞助
免责声明,若由于商用引起版权纠纷,一切责任均由使用者承担。
您必须遵守我们的协议,如您下载该资源,行为将被视为对《免责声明》全部内容的认可->联系老梁投诉资源 LaoLiang.Net部分资源来自互联网收集,仅供用于学习和交流,请勿用于商业用途。如有侵权、不妥之处,请联系站长并出示版权证明以便删除。
敬请谅解! 侵权删帖/违法举报/投稿等事物联系邮箱:service@laoliang.net
意在交流学习,欢迎赞赏评论,如有谬误,请联系指正;转载请注明出处: » 完整可以的WordPress文章远程(外链)图片自动保存本地化(亲测可用哦)
感谢分享,谢谢站长!!