get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE guid LIKE %s AND post_type = 'attachment'", '%' . $file ) ); if (!$attachment_id) { // Not found, import it // We use media_handle_sideload or similar internal functions, but since the file is already there, we can simulate an import. // Or simpler: just use shell_exec to call wp media import for this file if we are running in CLI context. // Given we are running via `wp eval-file`, we can shell out to `wp`. $cmd = "wp media import " . escapeshellarg($filepath) . " --porcelain --allow-root"; $output = shell_exec($cmd); $attachment_id = trim($output); if (!is_numeric($attachment_id)) { echo "Failed to import $file: $output\n"; continue; } echo "Imported $file as ID $attachment_id\n"; } else { echo "Found existing ID $attachment_id for $file\n"; } // Now assign to FileBird folder // Table: wp_fbv_attachment_folder (prefix might be different, let's use $wpdb->prefix) $table_name = $wpdb->prefix . 'fbv_attachment_folder'; // Check if entry exists $exists = $wpdb->get_var( $wpdb->prepare( "SELECT folder_id FROM $table_name WHERE attachment_id = %d", $attachment_id ) ); if ($exists) { if ($exists != $folder_id) { $wpdb->query( $wpdb->prepare( "UPDATE $table_name SET folder_id = %d WHERE attachment_id = %d", $folder_id, $attachment_id ) ); echo "Updated folder for ID $attachment_id 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 "Done. Processed/Assigned $count files.\n";