wordpress外链图片怎么自动下载到本地

Wordpress 思享 206浏览
摘要:
很多WordPress插件或代码在编辑文章时,可以自动将外部图片下载到本地。最后,我选择了一个叫易复制粘贴的插件。

WordPress很多插件或者代码都可以实现在编辑文章中自动将外链图片下载到本地,最终我选择了一个叫:Easy Copy Paste的插件。

大家可以自己后台下载下,我这里在提供一个代码版:

更容易使用~

加到当前主题函数模板 functions.php 中:

实现代码

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);

单篇操作

之后,编辑文章只需要点击更新按钮,就可以将文章中的外链图片下载到本地并替换链接。

不过逐个编辑文章不仅繁琐而且工作量不小,这里教大家一个小技巧,可以批量下载文章中的外链图片。

批量操作

该插件的代码不仅可以在正常的编辑页面点击更新按钮触发下载功能,而且可以在后台所有文章列表页面中触发下载图片功能,原理明白了,操作就简单了。

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

切记,不要更改批量编辑中的任何设置,只需单击 “更新”即可。

这个过程将触发检查所有选定的文章,并自动下载外链图片!

使用心得

遇到的问题

因为我在某函数中使用了wp_post_update()函数,会导致图片下载2份,至于我入门水平都没到,稀里糊涂的最后解决了这个问题

一种方法是将add_action这个动作加到了使用wp_post_update()的这个函数里面,同时也在wp_post_update()函数前添加remove_action动作

另外一种方法是删除掉函数传入$post,只传入$post_id,不过这样发布不会保存图片,但是需要再点一次更新。本人比较菜,如果有大佬也欢迎指正

扩展

可以修改如下代码,将图片文件的标题设置为发布文章的标题,其实也没有大用处,只是方便以后查找管理

'post_title' => preg_replace('/.[^.]+$/', '', $filename),

可以扩展自动为图片添加alt熟悉,这个可以参考《wordpress判断图片是否有alt属性,没有则添加标题为alt

推荐阅读

纯代码实现wordpress附件页面重定向到文章或首页

前几天发现wordpress网站有评论留言的回顾。结果一看就是附件页面的垃圾评论。这才发现原来wordpress上传的附件也会有对应的页面。难怪之前收录了很多附件页面,但是我的机器人禁止了,忘记了。本来以为会禁用,结果只找到了在线使用插件的方法。最后......

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function ‘fake_update_callback’

这是当一个被挂钩的函数名与挂钩关联不匹配时…这可能发生在重命名一个函数时,而不是在挂钩关联中重命名函数名时。如果强迫症受不了wordpress的主题提示,可以使用插件WP降级将版本设置为当前版本。...

wordpress升降到指定版本:WP Downgrade | Specific Core Version插件

背景:网站一直用4.9+版本,因为编辑器还是老的。如果是自动升级,是目前最高的版本,但是我想升级到最新的版本,4.9.22版。WP降级|特定核心版插件可以解决我的问题。设置好程序路径后,记得保存更改,然后“升/降级核心”会等待升级。如果是降级操作,为......