Thêm alt cho toàn bộ ảnh wordpress

// Chuyển tiêu đề tiếng Việt có dấu sang không dấu
function remove_vietnamese_accents($str) {
    if (class_exists('Transliterator')) {
        $transliterator = Transliterator::create('NFD; [:Nonspacing Mark:] Remove; NFC');
        return strtolower($transliterator->transliterate($str));
    }
    return strtolower($str);
}

// Đếm tổng số ảnh
function count_total_images() {
    $args = [
        'post_type'      => 'attachment',
        'post_mime_type' => 'image',
        'post_status'    => 'inherit',
        'fields'         => 'ids',
    ];
    $query = new WP_Query($args);
    return $query->found_posts;
}

// Cập nhật ALT cho tất cả ảnh
function update_all_image_alts() {
    $args = [
        'post_type'      => 'attachment',
        'post_mime_type' => 'image',
        'post_status'    => 'inherit',
        'posts_per_page' => -1, // Lấy toàn bộ ảnh
        'orderby'        => 'post_date',
        'order'          => 'DESC', // Ảnh mới nhất trước
    ];

    $images = get_posts($args);
    $total_images = count($images);
    $updated_count = 0;

    if ($total_images === 0) {
        error_log("❌ Không có ảnh nào để cập nhật ALT.");
        echo '<div class="notice notice-warning"><p>❌ Không có ảnh nào để cập nhật ALT.</p></div>';
        return;
    }

    foreach ($images as $image) {
        $parent_id = $image->post_parent;
        $alt_text = '';

        if ($parent_id) {
            $parent_title = get_the_title($parent_id);
            if (!empty($parent_title)) {
                $alt_text = remove_vietnamese_accents($parent_title);
            }
        }

        if (empty($alt_text)) {
            $alt_text = get_bloginfo('name'); // Dùng tiêu đề website nếu không có
        }

        update_post_meta($image->ID, '_wp_attachment_image_alt', sanitize_text_field($alt_text));
        $updated_count++;
    }

    error_log("✅ Đã cập nhật ALT cho $updated_count/$total_images ảnh.");
    echo '<div class="notice notice-success"><p>✅ Đã cập nhật ALT cho ' . $updated_count . ' ảnh.</p></div>';
}

// Chạy ngay lập tức khi admin vào Media
add_action('admin_init', 'update_all_image_alts');