Connecting Contact Form 7 to an external database

In this tutorial, you will learn how to create a custom WordPress plugin that connects the popular Contact Form 7 plugin with a database external to WordPress. By the end of this tutorial, you will have a plugin that saves data submitted through a contact form into an external database.

image 86

Preparation:

  1. Make sure you have Contact Form 7 installed and activated on your WordPress site.
  2. Create a form in Contact Form 7 and take note of the form ID that you will use in this tutorial.

Step 1: Set up the development environment

  1. In the wp-content/plugins folder of your WordPress installation, create a new folder named “cf7-external-db”.
  2. Inside this folder, create a file named “cf7-external-db.php” and include the following information in the file header:
<?php

Step 2: Establish the connection to the external database using $wpdb

Add the following global variables and the connection function in “cf7-external-db.php”:

// Replace with the connection details of your external database

Step 3: Send form data to the external database using $wpdb

Replace the function cf7_external_db_store_data in “cf7-external-db.php” with the following function that uses the class $wpdb to store the form data:

function cf7_external_db_store_data($cf7) {
    // Reemplaza con el ID de tu formulario de Contact Form 7
    $target_form_id = 123;
    
    if ($cf7->id() == $target_form_id) {
        $submission = WPCF7_Submission::get_instance();
        $data = $submission->get_posted_data();

        $name = isset($data['your-name']) ? sanitize_text_field($data['your-name']) : '';
        $email = isset($data['your-email']) ? sanitize_email($data['your-email']) : '';
        $message = isset($data['your-message']) ? sanitize_textarea_field($data['your-message']) : '';

        $wpdb_external = cf7_external_db_connect();

        $result = $wpdb_external->insert(
            'contact_form_entries',
            array(
                'name' => $name,
                'email' => $email,
                'message' => $message,
                'submitted_at' => current_time('mysql', 1)
            ),
            array('%s', '%s', '%s', '%s')
        );

        if ($result === false) {
            error_log('Error al insertar los datos en la base de datos externa: ' . $wpdb_external->last_error);
        }
    }
}
add_action('wpcf7_before_send_mail', 'cf7_external_db_store_data');

Step 4: Test the plugin

  1. Navigate to the WordPress admin panel and ensure that your plugin is activated.
  2. Go to the contact form page created in Contact Form 7 and submit some test data.
  3. Verify whether the submitted data was saved correctly in the external database using the class $wpdb.

Complete Code

<?php
/*
Plugin Name: Contact Form 7 - Base de datos externa
Plugin URI: https://tusitio.com/cf7-external-db
Description: Un plugin personalizado de WordPress para conectar Contact Form 7 con una base de datos externa.
Version: 1.0
Author: Tu nombre
Author URI: https://tusitio.com
License: GPL2
*/

// Reemplaza con los detalles de conexión de tu base de datos externa
define('CF7_EXTERNAL_DB_HOST', 'tu_host');
define('CF7_EXTERNAL_DB_USER', 'tu_usuario');
define('CF7_EXTERNAL_DB_PASSWORD', 'tu_contraseña');
define('CF7_EXTERNAL_DB_NAME', 'tu_base_de_datos');

function cf7_external_db_connect() {
    global $wpdb;
    
    $wpdb_external = new wpdb(CF7_EXTERNAL_DB_USER, CF7_EXTERNAL_DB_PASSWORD, CF7_EXTERNAL_DB_NAME, CF7_EXTERNAL_DB_HOST);
    $wpdb_external->set_prefix($wpdb->prefix);
    return $wpdb_external;
}

function cf7_external_db_store_data($cf7) {
    // Reemplaza con el ID de tu formulario de Contact Form 7
    $target_form_id = 123;
    
    if ($cf7->id() == $target_form_id) {
        $submission = WPCF7_Submission::get_instance();
        $data = $submission->get_posted_data();

        $name = isset($data['your-name']) ? sanitize_text_field($data['your-name']) : '';
        $email = isset($data['your-email']) ? sanitize_email($data['your-email']) : '';
        $message = isset($data['your-message']) ? sanitize_textarea_field($data['your-message']) : '';

        $wpdb_external = cf7_external_db_connect();

        $result = $wpdb_external->insert(
            'contact_form_entries',
            array(
                'name' => $name,
                'email' => $email,
                'message' => $message,
                'submitted_at' => current_time('mysql', 1)
            ),
            array('%s', '%s', '%s', '%s')
        );

        if ($result === false) {
            error_log('Error al insertar los datos en la base de datos externa: ' . $wpdb_external->last_error);
        }
    }
}
add_action('wpcf7_before_send_mail', 'cf7_external_db_store_data');
?>

Conclusion

Now you have a custom WordPress plugin that uses the class $wpdb to connect Contact Form 7 with an external database and store the data submitted through the form. You can continue customizing this plugin according to your needs.

Do you need help with a web project?

Do you need help with a web project? Don't hesitate to contact me. I develop complete and customized solutions with WordPress and PHP, using modern tools and processes, HTML, CSS, SCSS, PHP, JavaScript, Bootstrap, and more. Ready? Send me a message and let's talk about your web project!