<?php
// Regenera thumbnails de los attachments creados en /uploads/autores/joomla/
// Borra los thumbnails viejos y los recrea con las versiones face-cropped.
require '/var/www/html/wp-load.php';
require_once ABSPATH . 'wp-admin/includes/image.php';

global $wpdb;
$rows = $wpdb->get_results(
    "SELECT ID FROM {$wpdb->posts}
     WHERE post_type='attachment'
     AND guid LIKE '%/autores/joomla/%'"
);
echo 'Attachments: ' . count($rows) . PHP_EOL;

$uploads_basedir = wp_upload_dir()['basedir'];
$ok = 0; $fail = 0;
foreach ($rows as $r) {
    $aid = (int) $r->ID;
    $file = get_attached_file($aid);
    if (!$file || !file_exists($file)) { $fail++; continue; }

    // Borrar thumbnails viejos del attachment (todas las variantes -WxH)
    $old_meta = wp_get_attachment_metadata($aid);
    if (!empty($old_meta['sizes'])) {
        $dir = dirname($file);
        foreach ($old_meta['sizes'] as $s) {
            $thumb = $dir . '/' . $s['file'];
            if (file_exists($thumb)) @unlink($thumb);
        }
    }
    // Regenerar
    $meta = wp_generate_attachment_metadata($aid, $file);
    if ($meta) {
        wp_update_attachment_metadata($aid, $meta);
        $ok++;
    } else {
        $fail++;
    }
}
echo "OK: $ok, FAIL: $fail" . PHP_EOL;
