If you have ever wanted to customize a call to a webhook right after a submission of an Elementor Pro form, you would probably know that it is not as straightforward as you may think.
So I wanted to create a post that would at least try to explain the process of customization so that it is easier to understand. Let’s go.
Let's start with the basics.
Number one, how do you even customize the webhook calls? So the way to do it is to call hooks within Elementors API. What this means is this: you have to call a function that is called at a very specific predefined point. In this case the hook is called: elementor_pro/forms/new_record
add_action( 'elementor_pro/forms/new_record', 'send_custom_webhook', 10, 2 );
Ok, now where do we put the hook? I would say that the easiest way is to create a custom plugin or put it in the functions.php file in your theme folder.
Now the next step is to create the actual function that is going to run on that hook. We are calling it here send_custom_webhook.
function send_custom_webhook($record, $handler) {
//code goes here.
}
Now let’s use a code as example and we can then explain what it does at the end:
function send_custom_webhook( $record, $handler ) {
$form_name = $record->get_form_settings('form_name');
if ( 'My Form Name' !== $form_name ) {
return;
}
$raw_fields = $record->get( 'fields' );
$inbox_lead = [];
// We iterate over the fields.
foreach ( $raw_fields as $id => $field ) {
// Map
switch ($id) {
case 'first_name': // Adjust based on your form's field ID
$inbox_lead['first_name'] = $field['value'];
break;
case 'last_name':
$inbox_lead['last_name'] = $field['value'];
break;
case 'email':
$inbox_lead['email'] = $field['value'];
break;
case 'message':
$inbox_lead['message'] = $field['value'];
break;
}
}
// setup to data to an array called inbox_lead as an example.
$data = [
'inbox_lead' => $inbox_lead,
];
// Call the post webhook with the data encoded in JSON.
$response = wp_remote_post(
'https://api.service.com', // endpoint
[
'body' => json_encode($data),
'headers' => [
'Content-Type' => 'application/json',
'Accepts' => 'application/json'
// Auth if needed.
],
]
);
// Finally, let's have a way to know if the response from the service was successful or an error.
if (is_wp_error($response)) {
$error_message = $response->get_error_message();
$handler->add_response_data('custom_error', $error_message);
} else {
$body = wp_remote_retrieve_body($response);
// Assume the response body contains the message you want to display
$handler->add_response_data('custom_success', $body);
}
}
And that’s it. So in summary:
1. You use the right hook.
2. You attach the hook to a function
3. You write the customization function and include also a verification message so that you know if the response is working or not.
Until next time!