Plugin WordPress giúp bạn tự động lưu ảnh từ các bài viết (free)

cach-lay-kem-anh-khi-copy-bai-viet-trong-wordpress

Dưới đây là một plugin WordPress đơn giản giúp bạn tự động lưu ảnh từ các bài viết về local khi bạn copy nội dung có chứa ảnh (hotlink từ website khác) vào bài viết của mình.

Plugin này sẽ:

  • Tìm tất cả ảnh img trong nội dung bài viết.

  • Nếu ảnh đó không phải từ domain của bạn, nó sẽ:

    • Tải ảnh về thư viện media (media library).

    • Thay thế URL cũ bằng URL mới đã lưu về local.

  • 🚀 Tính năng mới:

    • 🔁 Ghi đè ảnh nếu tên trùng

    • 🏷️ Đổi tên ảnh theo tiêu đề bài viết (VD: bai-viet-moi-1.jpg)

    • 🔡 Chuyển tên về không dấu + lowercase + dấu gạch ngang — chuẩn SEO


✅ Bước 1: Tạo plugin

Bạn hãy tạo file mới trong thư mục wp-content/plugins/ với tên là auto-download-external-images.php và dán nội dung sau vào:

<?php
/*
Plugin Name: Auto Download Images On Save (No Duplicate + Rename)
Description: Tự động tải ảnh bên ngoài về Media, đổi tên ảnh, thay thế URL và tránh ảnh trùng lặp khi lưu bài viết.
Version: 1.4
Author: Bạn & ChatGPT
*/
add_action(‘save_post’, ‘adi_auto_download_images’);
function adi_auto_download_images($post_id) {
    if (
        wp_is_post_revision($post_id) ||
        (defined(‘DOING_AUTOSAVE’) && DOING_AUTOSAVE) ||
        !current_user_can(‘edit_post’, $post_id)
    ) return;
    $post = get_post($post_id);
    if (!$post || empty($post->post_content)) return;
    $content = $post->post_content;
    preg_match_all(‘/<img[^>]+src=[“\’]([^”\’]+)[“\’]/i’, $content, $matches);
    if (empty($matches[1])) return;
    require_once ABSPATH . ‘wp-admin/includes/media.php’;
    require_once ABSPATH . ‘wp-admin/includes/file.php’;
    require_once ABSPATH . ‘wp-admin/includes/image.php’;
    $site_host = parse_url(home_url(), PHP_URL_HOST);
    $upload_dir = wp_upload_dir();
    $updated = false;
    $index = 1;
    foreach ($matches[1] as $img_url) {
        $img_url = esc_url_raw($img_url);
        $img_host = parse_url($img_url, PHP_URL_HOST);
        if (!$img_host || strpos($img_host, $site_host) !== false) continue;
        // Lấy phần mở rộng
        $ext = pathinfo(parse_url($img_url, PHP_URL_PATH), PATHINFO_EXTENSION);
        $ext = strtolower($ext);
        if (!in_array($ext, [‘jpg’, ‘jpeg’, ‘png’, ‘gif’, ‘webp’])) continue;
        // Tạo tên mới dựa trên tiêu đề bài viết
        $base_name = adi_sanitize_filename($post->post_title);
        $new_filename = $base_name . ‘-‘ . $index . ‘.’ . $ext;
        $index++;
        $local_path = trailingslashit($upload_dir[‘path’]) . $new_filename;
        $new_url = trailingslashit($upload_dir[‘url’]) . $new_filename;
        // Nếu đã tồn tại → ghi đè
        if (file_exists($local_path)) {
            $image_data = wp_remote_get($img_url);
            if (!is_wp_error($image_data)) {
                file_put_contents($local_path, wp_remote_retrieve_body($image_data));
                $content = str_replace($img_url, $new_url, $content);
                $updated = true;
            }
        } else {
            // Tải về và ghi tên mới
            $tmp = download_url($img_url);
            if (!is_wp_error($tmp)) {
                $file_array = [
                    ‘name’     => $new_filename,
                    ‘tmp_name’ => $tmp,
                ];
                $id = media_handle_sideload($file_array, $post_id);
                if (!is_wp_error($id)) {
                    $file_url = wp_get_attachment_url($id);
                    $content = str_replace($img_url, $file_url, $content);
                    $updated = true;
                } else {
                    @unlink($tmp); // Xoá file tạm nếu lỗi
                }
            }
        }
    }
    if ($updated) {
        remove_action(‘save_post’, ‘adi_auto_download_images’);
        wp_update_post([
            ‘ID’ => $post_id,
            ‘post_content’ => $content,
        ]);
        add_action(‘save_post’, ‘adi_auto_download_images’);
    }
}
// Hàm tạo tên file thân thiện
function adi_sanitize_filename($str) {
    $str = remove_accents($str); // bỏ dấu tiếng Việt
    $str = strtolower($str);
    $str = preg_replace(‘/[^a-z0-9]+/’, ‘-‘, $str);
    $str = trim($str, ‘-‘);
    return $str;
}

✅ Bước 2: Kích hoạt plugin

  1. Vào Admin > Plugins (Gói mở rộng).

  2. Kích hoạt plugin Auto Download External Images.


✅ Kết quả

  • Khi bạn dán bài viết có chứa ảnh từ nơi khác (VD: copy từ trang khác có ảnh), khi nhấn lưu bài viết, plugin sẽ:

    • Tự động lưu ảnh về Media Library.

    • Tự động thay thế đường dẫn ảnh trong bài viết sang local.


Nếu bạn muốn mở rộng plugin này (hỗ trợ custom post types, hỗ trợ cronjob tự động), mình có thể giúp bạn nâng cấp thêm. Bạn muốn bổ sung tính năng nào không? Hãy liên hệ 0903.748.536 Website www.webbaoloc.com

Chat Zalo

0903748536