Press ESC to close

Chức năng tự động đổi tên file và nén ảnh sang webp khi upload trên WordPress

Giới thiệu

Khi vận hành một website WordPress, việc tối ưu hình ảnh là yếu tố quan trọng để tăng tốc độ tải trang, cải thiện điểm SEO và mang lại trải nghiệm người dùng tốt hơn. Để giải quyết điều này, bạn có thể sử dụng đoạn mã PHP dưới đây để:

  • ✅ Tự động nén ảnh khi upload lên WordPress
  • ✅ Chuyển đổi ảnh sang định dạng WebP siêu nhẹ
  • ✅ Đổi tên file ảnh theo tiêu đề bài viết

Không cần cài thêm plugin nào nặng nề — chỉ cần vài dòng code trong functions.php, website của bạn sẽ được tối ưu ảnh mạnh mẽ, chuyên nghiệp và thân thiện với SEO.


Lợi ích của đoạn mã

  • Tối ưu hóa hiệu suất website nhờ ảnh nhẹ hơn
  • Chuyển đổi ảnh sang WebP, nhẹ hơn JPEG/PNG đến 30-50%
  • Đổi tên file ảnh tự động theo bài viết, giúp quản lý dễ hơn và tăng khả năng hiển thị trên Google Image
  • Tự động resize ảnh lớn hơn 1920px, giúp tránh tải hình nặng không cần thiết

Đoạn mã hoàn chỉnh

Bạn chỉ cần sao chép đoạn mã sau vào cuối file functions.php của theme đang hoạt động (hoặc child theme)

/* xử lý đổi tên file và nén webp nhẹ hình, phát triển bởi gizadata.vn */

add_action('add_attachment', 'rename_uploaded_file');
add_filter('wp_handle_upload_prefilter', 'custom_upload_filter');

function rename_uploaded_file($attachment_id) {
    $post_id = wp_get_post_parent_id($attachment_id);
    if ($post_id) {
        $post_title = get_the_title($post_id);
        $post_title = substr($post_title, 0, 10);
        $file = get_attached_file($attachment_id);
        $path = pathinfo($file);

        $new_filename = sanitize_file_name($post_title) . '_' . $path['filename'] . '_' . wp_generate_password(4, false) . '.' . $path['extension'];
        $new_file = $path['dirname'] . '/' . $new_filename;

        rename($file, $new_file);
        update_attached_file($attachment_id, $new_file);
    }
}

function custom_upload_filter($file) {
    add_filter('wp_handle_upload', 'custom_resize_compress_to_webp');

    $post_id = $_REQUEST['post_id'] ?? 0;
    $post_title = $post_id ? get_the_title($post_id) : 'image';
    $post_title = substr($post_title, 0, 20);
    $file['name'] = wp_unique_filename($file['upload_path'], sanitize_file_name($post_title) . '_' . $file['name']);
    $file['name'] = pathinfo($file['name'], PATHINFO_FILENAME) . '_' . wp_generate_password(4, false) . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
    return $file;
}

function custom_resize_compress_to_webp($upload) {
    $file_path = $upload['file'];
    $image_info = getimagesize($file_path);

    if (!$image_info) return $upload;

    $width = $image_info[0];
    $mime = $image_info['mime'];
    $max_width = 1920;

    $editor = wp_get_image_editor($file_path);
    if (is_wp_error($editor)) return $upload;

    if ($width > $max_width) {
        $editor->resize($max_width, null);
    }

    $pathinfo = pathinfo($file_path);
    $new_path = $pathinfo['dirname'] . '/' . $pathinfo['filename'] . '.webp';

    $saved = $editor->save($new_path, 'image/webp');

    if (!is_wp_error($saved)) {
        unlink($file_path);
        $upload['file'] = $new_path;
        $upload['url'] = dirname($upload['url']) . '/' . basename($new_path);
        $upload['type'] = 'image/webp';
    }

    return $upload;
}

Hướng dẫn sử dụng

  1. Truy cập thư mục theme: wp-content/themes/ten-theme-cua-ban/
  2. Mở file functions.php
  3. Dán đoạn mã vào cuối file
  4. Lưu lại và thử upload ảnh mới

Hình ảnh mới sẽ:

  • Tự động đổi tên theo tiêu đề bài viết
  • Resize nếu vượt quá 1920px
  • Chuyển sang định dạng .webp
  • Giảm kích thước tối đa mà vẫn giữ chất lượng ổn
0 0 đánh giá
Đánh giá bài viết
Theo dõi
Thông báo của
guest
0 Góp ý
Cũ nhất
Mới nhất Được bỏ phiếu nhiều nhất
Phản hồi nội tuyến
Xem tất cả bình luận
by CUONGIT