Breakdance Forms to Klaviyo Integration

The CWPKlaviyoAction class provides a seamless integration between WordPress forms and Klaviyo. When a form is submitted, the run method is invoked, extracting the name and email from the submission and sending it to Klaviyo. It includes error handling for a robust solution.

<?php // 1. Create an action class to represent your field class CWPKlaviyoAction extends \Breakdance\Forms\Actions\Action { // The name method returns a string used to identify the action in the Form Builder Actions dropdown public static function name() { return 'Klaviyo Action'; } // The slug method returns a string to uniquely identify the form action public static function slug() { return 'cwp_klaviyo_form_action'; } // The run method is triggered when the form is submitted public function run($form, $settings, $extra) { try { // Extract the name and email fields from the form submission $name = $extra['fields']['name']; $email = $extra['fields']['email']; // Send the name and email to Klaviyo (For simplicity, the actual Klaviyo API call is not implemented) $this->sendToKlaviyo($name, $email); // Return success message after sending data to Klaviyo return ['type' => 'success', 'message' => 'Data sent to Klaviyo']; } catch (Exception $e) { // Return error message in case of any exceptions return ['type' => 'error', 'message' => $e->getMessage()]; } } private function sendToKlaviyo($name, $email) { $data = [ 'type' => 'profile', 'attributes' => [ 'email' => $email, 'first_name' => $name ] ]; $args = [ 'headers' => [ 'Authorization' => 'Klaviyo-API-Key your-private-api-key', 'Accept' => 'application/json', 'Content-Type' => 'application/json', 'Revision' => '2024-02-15' ], 'body' => json_encode($data), 'method' => 'POST', 'data_format' => 'body' ]; $response = wp_remote_post('https://a.klaviyo.com/api/profiles/', $args); if (is_wp_error($response)) { $error_message = $response->get_error_message(); echo "Something went wrong: $error_message"; } else { echo 'Response:<pre>'; print_r($response); echo '</pre>'; } } } // 2. Register the action class with Breakdance // Use the WordPress 'init' action to register the action class, ensuring the Breakdance is installed and available add_action('init', function () { if (!function_exists('\Breakdance\Forms\Actions\registerAction') || !class_exists('\Breakdance\Forms\Actions\Action')) { return; } // Register the action with Breakdance \Breakdance\Forms\Actions\registerAction(new CWPKlaviyoAction()); });

Frequently Asked Questions

CWPKlaviyoAction is a custom action class for integrating WordPress forms with Klaviyo, allowing form submissions to be sent directly to Klaviyo.