prefix . 'fbv_attachment_folder'; if (!is_dir($base_dir)) { die("Directory not found: $base_dir\n"); } echo "Starting Import for $relative_base (ID: $folder_id)...\n"; $files = scandir($base_dir); $count_existing = 0; $count_new = 0; $count_assigned = 0; $errors = 0; foreach ($files as $file) { if ($file === '.' || $file === '..') continue; $filepath = $base_dir . '/' . $file; if (is_dir($filepath)) continue; $guid_search = '%' . $relative_base . '/' . $file; $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) { $cmd = "wp media import " . escapeshellarg($filepath) . " --porcelain --allow-root"; $output = shell_exec($cmd); $attachment_id = trim($output); if (!is_numeric($attachment_id)) { $errors++; continue; } $count_new++; $wpdb->query( $wpdb->prepare( "INSERT INTO $table_name (folder_id, attachment_id) VALUES (%d, %d)", $folder_id, $attachment_id ) ); $count_assigned++; } else { $count_existing++; $current_folder = $wpdb->get_var( $wpdb->prepare( "SELECT folder_id FROM $table_name WHERE attachment_id = %d", $attachment_id ) ); if ($current_folder != $folder_id) { if ($current_folder) { $wpdb->query( $wpdb->prepare( "UPDATE $table_name SET folder_id = %d WHERE attachment_id = %d", $folder_id, $attachment_id ) ); } else { $wpdb->query( $wpdb->prepare( "INSERT INTO $table_name (folder_id, attachment_id) VALUES (%d, %d)", $folder_id, $attachment_id ) ); } $count_assigned++; } } } echo "\nCompleted $relative_base.\nTotal: " . ($count_existing + $count_new) . "\nNew: $count_new\nErrors: $errors\n";