'Musica', 8 => 'Pensamientos', 9 => 'Portadas', 10 => 'homilias_fray_marcos', 11 => 'stories', 12 => '1jornada_feadulta' ]; global $wpdb; $table_name = $wpdb->prefix . 'fbv_attachment_folder'; foreach ($mappings as $folder_id => $relative_base) { echo "Processing Folder: $relative_base (ID: $folder_id)...\n"; $base_dir = '/var/www/html/wp-content/uploads/' . $relative_base; if (!is_dir($base_dir)) { echo "Directory not found: $base_dir\n"; continue; } $files = scandir($base_dir); $count = 0; $errors = 0; foreach ($files as $file) { if ($file === '.' || $file === '..') continue; $filepath = $base_dir . '/' . $file; if (is_dir($filepath)) continue; // Find attachment ID // Try exact match on GUID first (most reliable for migrated files) // GUIDs usually store path relative to uploads, but sometimes absolute // We use LIKE to be safe: %relative_base/file $guid_search = '%' . $relative_base . '/' . $file; // Check if exists in DB $attachment_id = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE guid LIKE %s AND post_type = 'attachment'", $guid_search ) ); if (!$attachment_id) { echo "Importing: $file\n"; // Use wp media import $cmd = "wp media import " . escapeshellarg($filepath) . " --porcelain --allow-root"; $output = shell_exec($cmd); $attachment_id = trim($output); if (!is_numeric($attachment_id)) { echo " ERROR: Failed to import $file. Output: $output\n"; $errors++; continue; } } // Assign to folder $current_folder = $wpdb->get_var( $wpdb->prepare( "SELECT folder_id FROM $table_name WHERE attachment_id = %d", $attachment_id ) ); if ($current_folder) { if ($current_folder != $folder_id) { $wpdb->query( $wpdb->prepare( "UPDATE $table_name SET folder_id = %d WHERE attachment_id = %d", $folder_id, $attachment_id ) ); echo " Moved ID $attachment_id from folder $current_folder to $folder_id\n"; $count++; } } else { $wpdb->query( $wpdb->prepare( "INSERT INTO $table_name (folder_id, attachment_id) VALUES (%d, %d)", $folder_id, $attachment_id ) ); echo " Assigned ID $attachment_id to folder $folder_id\n"; $count++; } } echo "Completed $relative_base. Assigned/Moved: $count files. Errors: $errors.\n"; }