WordPress 批量将文章中的外链图片导入到本地

据报,新浪博客已正式宣布“相册”功能下线,最后期限是 2019 年 7 月 31 日 24 时,又一个免费的午餐没了。如何把放在新浪相册的图片下载到本地并替换原来的链接,摆在了众多使用新浪免费图床用户面前,当然也包括我。经多方查找测试,将本人最终解决办法,分享给大家。wordpress 很多插件或者代码都可以实现在编辑文章中自动将外链图片下载到本地,最终我选择了一个叫:Easy Copy Paste的插件。

代码实现

也可以直接将下面的代码,添加到当前主题函数模板 functions.php 中:

  1.     function ecp_save_post($post_id, $post) {
  2.     global $wpdb;
  3.     if($post->post_status == 'publish') {
  4.     $p   = '/<img.*[\s]src=[\"|\'](.*)[\"|\'].*>/iU';
  5.     $num = preg_match_all($p, $post->post_content, $matches);
  6.     if ($num) {
  7.     $wp_upload_dir = wp_upload_dir();
  8.     set_time_limit(0);
  9.     $ch = curl_init();
  10.     curl_setopt($ch, CURLOPT_HEADER, false);
  11.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  12.     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  13.     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  14.     curl_setopt($ch, CURLOPT_MAXREDIRS,20);
  15.     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
  16.  
  17.     $ecp_options = $_SERVER['HTTP_HOST'];
  18.     foreach ($matches[1] as $src) {
  19.     if (isset($src) && strpos($src, $ecp_options) === false) {
  20.     $file_info = wp_check_filetype(basename($src), null);
  21.     if ($file_info['ext'] == false) {
  22.     date_default_timezone_set('PRC');
  23.     $file_name = date('YmdHis-').dechex(mt_rand(100000, 999999)).'.tmp';
  24.     } else {
  25.     $file_name = dechex(mt_rand(100000, 999999)) . '-' . basename($src);
  26.     }
  27.     curl_setopt($ch, CURLOPT_URL, $src);
  28.     $file_path = $wp_upload_dir['path'] . '/' . $file_name;
  29.     $img = fopen($file_path, 'wb');
  30.     curl_setopt($ch, CURLOPT_FILE, $img);
  31.     $img_data  = curl_exec($ch);
  32.     fclose($img);
  33.  
  34.     if (file_exists($file_path) && filesize($file_path) > 0) {
  35.     $t   = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
  36.     $arr = explode('/', $t);
  37.     if (pathinfo($file_path, PATHINFO_EXTENSION) == 'tmp') {
  38.     $file_path = ecp_handle_ext($file_path, $arr[1], $wp_upload_dir['path'], $file_name, 'tmp');
  39.     } elseif (pathinfo($file_path, PATHINFO_EXTENSION) == 'webp') {
  40.     $file_path = ecp_handle_ext($file_path, $arr[1], $wp_upload_dir['path'], $file_name, 'webp');
  41.     }
  42.     $post->post_content  = str_replace($src, $wp_upload_dir['url'] . '/' . basename($file_path), $post->post_content);
  43.     $attachment = ecp_get_attachment_post(basename($file_path), $wp_upload_dir['url'] . '/' . basename($file_path));
  44.     $attach_id = wp_insert_attachment($attachment, ltrim($wp_upload_dir['subdir'] . '/' . basename($file_path), '/'), 0);
  45.     $attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
  46.     $ss = wp_update_attachment_metadata($attach_id, $attach_data);
  47.     }
  48.     }
  49.     }
  50.     curl_close($ch);
  51.     $wpdb->update( $wpdb->posts, array('post_content' => $post->post_content), array('ID' => $post->ID));
  52.     }
  53.     }
  54.     }
  55.  
  56.     function ecp_handle_ext($file, $type, $file_dir, $file_name, $ext) {
  57.     switch ($ext) {
  58.     case 'tmp':
  59.     if (rename($file, str_replace('tmp', $type, $file))) {
  60.     if ('webp' == $type) {
  61.     return ecp_image_convert('webp', 'jpeg', $file_dir . '/' . str_replace('tmp', $type, $file_name));
  62.     }
  63.     return $file_dir . '/' . str_replace('tmp', $type, $file_name);
  64.     }
  65.     case 'webp':
  66.     if ('webp' == $type) {
  67.     return ecp_image_convert('webp', 'jpeg', $file);
  68.     } else {
  69.     if (rename($file, str_replace('webp', $type, $file))) {
  70.     return $file_dir . '/' . str_replace('webp', $type, $file_name);
  71.     }
  72.     }
  73.     default:
  74.     return $file;
  75.     }
  76.     }
  77.  
  78.     function ecp_image_convert($from='webp', $to='jpeg', $image) {
  79.     $im = imagecreatefromwebp($image);
  80.     if (imagejpeg($im, str_replace('webp', 'jpeg', $image), 100)) {
  81.     try {
  82.     unlink($image);
  83.     } catch (Exception $e) {
  84.     $error_msg = sprintf('Error removing local file %s: %s', $image,
  85.     $e->getMessage());
  86.     error_log($error_msg);
  87.     }
  88.     }
  89.     imagedestroy($im);
  90.  
  91.     return str_replace('webp', 'jpeg', $image);
  92.     }
  93.  
  94.     function ecp_get_attachment_post($filename, $url) {
  95.     $file_info  = wp_check_filetype($filename, null);
  96.     return array(
  97.     'guid'           => $url,
  98.     'post_type'      => 'attachement',
  99.     'post_mime_type' => $file_info['type'],
  100.     'post_title'     => preg_replace('/\.[^.]+$/', '', $filename),
  101.     'post_content'   => '',
  102.     'post_status'    => 'inherit'
  103.     );
  104.     }
  105.     add_action('save_post', 'ecp_save_post', 120, 2);

单篇操作

之后,编辑文章只需要点击更新按钮,就可以将文章中的外链图片下载到本地并替换链接。不过逐个编辑文章不仅繁琐而且工作量不小,这里教大家一个小技巧,可以批量下载文章中的外链图片。该插件的代码不仅可以在正常的编辑页面点击更新按钮触发下载功能,而且可以在后台所有文章列表页面中触发下载图片功能,原理明白了,操作就简单了。

批量操作

进入 WP 后台,文章→所有文章,进入文章管理页面,勾选“标题”全选当前页面的所有文章,并选择“编辑”,并点击“应用”按钮。

切记,不要更改批量编辑中的任何设置,只需单击 “更新”即可。这个过程将触发检查所有选定的文章,并导入外链图片。默认每页只显示 20 篇文章,如果你的文章较多,并想一次性处理更多的文章,可以打开右上角的“显示选项”,将“每页的项目数”调整为 9999,当然要视你的主机配置适当调整文章数量,一次性处理太多文章,会让主机瞬间资源耗尽,造成宕机。
提示:操作前请提前做好数据库备份,以防万一,祝大家图片逃亡成功!

© 版权声明
THE END
喜欢就支持以下吧
点赞0赞赏
分享
相关推荐
  • 暂无相关文章
评论 抢沙发