
Đôi khi bạn copy 1 bài viết từ website khác sang website của bạn. Về mặt hiển thị nó sẽ tương tự, nhưng thực chất ảnh của bài viết đó đang sử dụng đường link của website nguồn. Bạn cần phải tài về để thay thế từng ảnh đó, nên mình làm bài viết này giúp cho việc đó tự động khi bạn lưu bài viết.
Hãy thêm vào file functions.php
php
Sao chép
class Auto_Save_External_Images {
public function __construct() {
add_filter('content_save_pre', array($this, 'save_external_images_to_media'));
}
public function save_external_images_to_media($content) {
if (isset($_POST['save']) || isset($_POST['publish'])) {
set_time_limit(240);
global $post;
if (!is_object($post) || empty($post->ID)) return $content;
$post_id = $post->ID;
$host = $_SERVER['HTTP_HOST'];
// Tìm tất cả các ảnh
preg_match_all('/<img[^>]+src=[\'"]([^\'"]+)[\'"]/i', stripslashes($content), $matches);
if (!empty($matches[1])) {
foreach ($matches[1] as $image_url) {
if (empty($image_url)) continue;
$img_host = parse_url($image_url, PHP_URL_HOST);
if ($img_host && $img_host !== $host) {
// Là ảnh ngoài -> tải về
$res = $this->download_image($image_url, $post_id);
if (!empty($res['url'])) {
$content = str_replace($image_url, $res['url'], $content);
}
}
}
}
}
// Chỉ xử lý 1 lần
remove_filter('content_save_pre', array($this, 'save_external_images_to_media'));
return $content;
}
private function download_image($image_url, $post_id) {
$image_data = @file_get_contents($image_url);
if ($image_data === false) return ['url' => $image_url]; // fallback giữ nguyên link
$post = get_post($post_id);
$post_title = sanitize_title($post->post_title);
$ext = pathinfo(parse_url($image_url, PHP_URL_PATH), PATHINFO_EXTENSION);
if (!$ext) $ext = 'jpg';
$filename = $post_title . '-' . $post_id . '-' . md5($image_url) . '.' . $ext;
$upload = wp_upload_bits($filename, null, $image_data);
if (!$upload || !empty($upload['error'])) return ['url' => $image_url];
$this->attach_to_post($upload['file'], $post_id);
return $upload;
}
private function attach_to_post($filepath, $post_id) {
$wp_filetype = wp_check_filetype($filepath);
$upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $upload_dir['url'] . '/' . basename($filepath),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filepath)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $filepath, $post_id);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata($attach_id, $filepath);
wp_update_attachment_metadata($attach_id, $attach_data);
}
}
new Auto_Save_External_Images();
Bình luận