远程图片本地化可以解决很多问题,比如抄袭,复制粘贴,虽然我们不提倡这样做。但是在某些特殊情况下可能会用到。
本文给大家推荐两种不使用插件的方法。(如果图片格式是jpeg有时候无法保存,jpg和png、gif都可以成功,另外有可能会导致后台插入图片的时候提示“上传时发生了错误。请稍后再试。”)

第一种将以下代码写入主题的functions.php文件或者是functions.php的引入文件中即可:

  1. //远程图片本地化
  2. add_filter('content_save_pre', 'auto_save_image');
  3. function auto_save_image($content) {
  4. $upload_path = '';
  5. $upload_url_path = get_bloginfo('url');
  6. //上传目录
  7. if (($var = get_option('upload_path')) !=''){
  8. $upload_path = $var;
  9. else {
  10. $upload_path = 'wp-content/uploads';
  11. }
  12. if(get_option('uploads_use_yearmonth_folders')) {
  13. $upload_path .= '/'.date("Y",time()).'/'.date("m",time());
  14. }
  15. //文件地址
  16. if(($var = get_option('upload_url_path')) != '') {
  17. $upload_url_path = $var;
  18. else {
  19. $upload_url_path = bloginfo('url');
  20. }
  21. if(get_option('uploads_use_yearmonth_folders')) {
  22. $upload_url_path .= '/'.date("Y",time()).'/'.date("m",time());
  23. }
  24. require_once ("../wp-includes/class-snoopy.php");
  25. $snoopy_Auto_Save_Image = new Snoopy;
  26. $img = array();
  27. //以文章的标题作为图片的标题
  28. if ( !emptyempty$_REQUEST['post_title'] ) )
  29. $post_title = wp_specialchars( stripslashes$_REQUEST['post_title'] ));
  30. $text = stripslashes($content);
  31. if (get_magic_quotes_gpc()) $text = stripslashes($text);
  32. preg_match_all("/ src=("|'){0,}(http://(.+?))("|'|s)/is",$text,$img);
  33. $img = array_unique(dhtmlspecialchars($img[2]));
  34. foreach ($img as $key => $value){
  35. set_time_limit(180); //每个图片最长允许下载时间,秒
  36. if(str_replace(get_bloginfo('url'),"",$value)==$value&&str_replace(get_bloginfo('home'),"",$value)==$value){
  37. //判断是否是本地图片,如果不是,则保存到服务器
  38. $fileext = substr(strrchr($value,'.'),1);
  39. $fileext = strtolower($fileext);
  40. if($fileext==""||strlen($fileext)>4)
  41. $fileext = "jpg";
  42. $savefiletype = array('jpg','gif','png','bmp');
  43. if (in_array($fileext$savefiletype)){
  44. if($snoopy_Auto_Save_Image->fetch($value)){
  45. $get_file = $snoopy_Auto_Save_Image->results;
  46. }else{
  47. echo "error fetching file: ".$snoopy_Auto_Save_Image->error."
  48. ";
  49. echo "error url: ".$value;
  50. die();
  51. }
  52. $filetime = time();
  53. $filepath = "/".$upload_path;//图片保存的路径目录
  54. !is_dir("..".$filepath) ? mkdirs("..".$filepath) : null;
  55. //$filename = date("His",$filetime).random(3);
  56. $filename = substr($value,strrpos($value,'/'),strrpos($value,'.')-strrpos($value,'/'));
  57. //$e = '../'.$filepath.$filename.'.'.$fileext;
  58. //if(!is_file($e)) {
  59. // copy(htmlspecialchars_decode($value),$e);
  60. //}
  61. $fp = @fopen("..".$filepath.$filename.".".$fileext,"w");
  62. @fwrite($fp,$get_file);
  63. fclose($fp);
  64. $wp_filetype = wp_check_filetype( $filename.".".$fileext, false );
  65. $type = $wp_filetype['type'];
  66. $post_id = (int)$_POST['temp_ID2'];
  67. $title = $post_title;
  68. $url = $upload_url_path.$filename.".".$fileext;
  69. $file = $_SERVER['DOCUMENT_ROOT'].$filepath.$filename.".".$fileext;
  70. //添加数据库记录
  71. $attachment = array(
  72. 'post_type' => 'attachment',
  73. 'post_mime_type' => $type,
  74. 'guid' => $url,
  75. 'post_parent' => $post_id,
  76. 'post_title' => $title,
  77. 'post_content' => '',
  78. );
  79. $id = wp_insert_attachment($attachment$file$post_parent);
  80. $text = str_replace($value,'http://www.zswu.net/wp-content/uploads'.$url,$text); //替换里面的网址成自己的
  81. }
  82. }
  83. }
  84. $content = AddSlashes($text);
  85. remove_filter('content_save_pre', 'auto_save_image');
  86. return $content;
  87. }
  88. function mkdirs($dir)
  89. {
  90. if(!is_dir($dir))
  91. {
  92. mkdirs(dirname($dir));
  93. mkdir($dir);
  94. }
  95. return ;
  96. }
  97. function dhtmlspecialchars($string) {
  98. if(is_array($string)) {
  99. foreach($string as $key => $val) {
  100. $string[$key] = dhtmlspecialchars($val);
  101. }
  102. }else{
  103. $string = str_replace('&', '&', $string);
  104. $string = str_replace('"', '"', $string);
  105. $string = str_replace('<', '<', $string); $string = str_replace('>', '>', $string);
  106. $string = preg_replace('/&(#d;)/', '&1', $string);
  107. }
  108. return $string;
  109. }
  110. //远程图片本地化结束

第二种和上面一样,将以下代码写入主题的functions.php文件或者是functions.php的引入文件中即可:

  1. /************自动下载外部图片开始**************/
  2. //多级目录创建
  3. function mkdirs($dir){
  4. if(!is_dir($dir)){
  5. if(!$this-&gt;mkdirs(dirname($dir))){
  6. return false;
  7. }
  8. if(!mkdir($dir,0777, true)){
  9. return false;
  10. }
  11. }
  12. return true;
  13. } </code>
  14. function save_post_fix($content){
  15. $post_id = get_the_ID();
  16. $upload_dir = wp_upload_dir();
  17. $path = $upload_dir["url"];
  18. $realPath = $upload_dir["path"];
  19. if(!is_dir($realPath)){
  20. mkdirs($realPath);
  21. }
  22. $pagelink=array();
  23. $pattern_page = '/&lt;img([sS]*?)src=["|'](.*?)["|']([sS]*?)&gt;/i';
  24. preg_match_all($pattern_page$content$pagelink[]);
  25. foreach ($pagelink[0][2] as $key =&gt; $value) {
  26. $pic_url = $value;
  27. $url_feter = parse_url($pic_url);
  28. if(stripos($url_feter["host"],"zhnytech.com")){
  29. continue;
  30. }else{
  31. $ch = curl_init(); // 启动一个CURL会话
  32. curl_setopt($ch,CURLOPT_HEADER,1); //不示返回的Header区域内容
  33. curl_setopt($ch, CURLOPT_NOBODY, TRUE);
  34. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  35. curl_setopt($ch,CURLOPT_URL,$pic_url);
  36. $hd = curl_exec($ch);
  37. if(!emptyempty($hd) &amp;&amp; !(strpos($hd,'Content-Length: image/png')||strpos($hd,'Content-Length: image/jpg'))){
  38. $fp =file_get_contents($pic_url);
  39. $pic_name =basename($url_feter["path"]);
  40. $savePath = $realPath.'/'.$pic_name;
  41. $fullPath = $path.'/'.$pic_name;
  42. if(file_exists($savePath)){
  43. $savePath = $realPath.'/'.str_replace('.','-'.date("s").'.' ,$pic_name);
  44. $fullPath = $path.'/'.str_replace('.','-'.date("s").'.' ,$pic_name);
  45. }
  46. if(file_put_contents($savePath,$fp)){
  47. $content = str_replace($pic_url$fullPath$content);
  48. //插数据库生成预览图
  49. $wp_filetype = wp_check_filetype(basename($savePath), null );
  50. $wp_upload_dir = wp_upload_dir();
  51. $attachment = array(
  52. 'guid' =&gt; $wp_upload_dir['url'] . '/' . basename$savePath ),
  53. 'post_mime_type' =&gt; $wp_filetype['type'],
  54. 'post_title' =&gt; preg_replace( '/.[^.]+$/', ''basename$savePath ) ),
  55. 'post_content' =&gt; '',
  56. 'post_status' =&gt; 'inherit'
  57. );
  58. $attach_id = wp_insert_attachment( $attachment$savePath$post_id );
  59. require_once( ABSPATH . 'wp-admin/includes/image.php' );
  60. $attach_data = wp_generate_attachment_metadata( $attach_id$savePath );
  61. wp_update_attachment_metadata( $attach_id$attach_data );
  62. }
  63. }
  64. }
  65. }
  66. return $content;
  67. }
  68. add_filter( 'content_save_pre', 'save_post_fix', 90, 1 );
  69. /************自动下载外部图片结束**************/

两种方法都可以,大家可以测试看看。以后每当在wordpress发布文章时如果文章中含有外链图片就会自动本地化了,无需任何设置操作非常方便。

豫ICP备11029947号