How to Send Contact Form Data to an External Endpoint in WordPress

Contact forms are an essential feature for websites, allowing visitors to easily get in touch. In WordPress, there are several popular plugins for creating and managing contact forms, including:

Each of these plugins offers customization options and integrations, making them versatile for different use cases.

Sometimes, you may need to send the data submitted via a contact form to an external endpoint. Common scenarios include:

  • Sending data to a CRM or email marketing tool for lead tracking.
  • Integrating with an API for order tracking or support ticketing systems.
  • Logging submissions to a custom database or external application for reporting.

How to extend Contact Form 7 to send data to an external endpoint after submission

Below is an example of how to extend Contact Form 7 to send data to an external endpoint after submission:

What is wpcf7_before_send_mail hook?

wpcf7_before_send_mail is a WordPress action hook provided by the Contact Form 7 plugin. It allows developers to execute custom code right before the form’s email is sent.

This is particularly useful for modifying the email content, saving form submissions to the database, or sending the data to an external API.

// Send form data after submission
add_action('wpcf7_before_send_mail', 'trimite_date_custom');

function trimite_date_custom($contact_form) {
    // Log the submission for debugging
    error_log('Form submitted!');

    // Retrieve form data
    $submission = WPCF7_Submission::get_instance();
    if ($submission) {
        $data = $submission->get_posted_data();
        error_log('Form data: ' . print_r($data, true));

        // Example: Send data to an external API endpoint
        $endpoint_url = 'https://example.com/api/track-form-submission';
        $response = wp_remote_post($endpoint_url, [
            'body' => $data,
        ]);

        if (is_wp_error($response)) {
            error_log('Error sending data: ' . $response->get_error_message());
        } else {
            error_log('Data sent successfully: ' . print_r($response, true));
        }
    }
}

By sending form data to an external endpoint, you can integrate your contact forms with various tools and systems, making them even more powerful.

Whether you’re tracking leads, automating responses, or enhancing user experience, this approach opens up many possibilities.

Hello there!

I hope you find this post useful!

I'm Mihai, a programmer and online marketing specialist, very passionate about everything that means online marketing, focused on eCommerce.

If you have a collaboration proposal or need helps with your projects feel free to contact me. I will always be glad to help you!

Leave a Comment

WebPedia.net