Streamlining WPForms Dynamic Lead Matching

Are you tired of juggling multiple WPForms for different clients and struggling to manage countless notifications? Do you find it cumbersome to update long lists of email recipients whenever there’s a change? If so, you’re not alone. Many businesses face these challenges when using WPForms for lead management, especially when dealing with a large number of clients or dealerships.

Fortunately, there’s a solution that can simplify your lead management process and make it more scalable. By leveraging custom PHP code and the WPForms API, you can dynamically match customer inquiries with the relevant dealerships, eliminating the need for multiple forms and complex notification setups.

The Problem with Traditional WPForms Lead Management

WPForms offers powerful form-building capabilities, but its built-in lead management features can become limiting in certain scenarios. For example:

  • Multiple Forms: If you work with multiple clients or dealerships, you might need to create a separate form for each one, leading to a cluttered and difficult-to-manage setup.
  • Numerous Notifications: Each form might require multiple notifications to send emails to different recipients based on conditional logic. This can quickly become overwhelming and error-prone.
  • Static Recipient Lists: WPForms notifications rely on static lists of email addresses. Updating these lists can be time-consuming and increases the risk of mistakes.

The Solution: Dynamic Dealership Matching

				
					/**
 * Handles sending emails to matching dealerships after a WPForms submission.
 *
 * @param array $fields  The submitted form fields.
 * @param object $entry  The WPForms entry object.
 * @param array $form_data  The form data.
 * @param int $entry_id  The entry ID.
 */
function send_email_to_matching_dealerships($fields, $entry, $form_data, $entry_id) {
    // Form and field configuration (replace with your actual IDs)
    $config = array(
        'customer_form_id' => 437,
        'dealership_form_id' => 235,
        'customer_form_fields' => array(
            'name' => 28,
            'email' => 3,
            'phone' => 2,
            'location' => 27,
            'manufacturer' => 25,
            'specific_vehicle' => 5,
            'price_range' => 26,
            'contact_method' => 17,
            'finance_options' => 6,
            'open_to_suggestions' => 21,
            'additional_info' => 10,
            'consent' => 11
        ),
        'dealership_form_fields' => array(
            'email' => 2,
            'manufacturer' => 7,
            'location' => 4
        ),
        'email_subject' => 'Incoming Lead from SpotMyRide',
        'no_match_email_subject' => 'No Matching Dealerships Found',
        'no_match_message' => 'No matching dealerships were found for your inquiry. We will keep your information on file and contact you if any suitable options become available.'
    );

    // Process only if it's the customer form and fields are valid
    if ($form_data['id'] == $config['customer_form_id'] && validate_form_fields($fields, $config['customer_form_fields'])) {
        // Extract customer data
        $customer_data = extract_form_data($fields, $config['customer_form_fields']);

        // Log customer inquiry for debugging
        error_log('Customer Inquiry: ' . print_r($customer_data, true));

        // Find matching dealerships
        $matching_dealerships = get_matching_dealerships(
            $config['dealership_form_id'], 
            $customer_data['manufacturer'], 
            $customer_data['location'], 
            $config['dealership_form_fields']
        );

        if (!empty($matching_dealerships)) {
            // Send emails to matching dealerships
            foreach ($matching_dealerships as $dealership) {
                send_email_to_dealership($dealership, $customer_data, $config['dealership_form_fields'], $config['email_subject']);
            }
        } else {
            // Handle no matching dealerships 
            handle_no_matching_dealerships($customer_data, $config);
        }
    }
}

/**
 * Validates if all required form fields are present and have values.
 *
 * @param array $fields  The submitted form fields.
 * @param array $required_fields  An array mapping field names to their IDs.
 * @return bool  True if all required fields are valid, false otherwise.
 */
function validate_form_fields($fields, $required_fields) {
    foreach ($required_fields as $field_name => $field_id) {
        if (!isset($fields[$field_id]) || empty($fields[$field_id]['value'])) {
            error_log("Missing or empty field: $field_name (ID: $field_id)");
            return false;
        }
    }
    return true;
}

/**
 * Extracts data from form fields based on a field map.
 *
 * @param array $fields  The submitted form fields.
 * @param array $field_map  An array mapping field names to their IDs.
 * @return array  An associative array of extracted field data.
 */
function extract_form_data($fields, $field_map) {
    $data = array();
    foreach ($field_map as $field_name => $field_id) {
        $data[$field_name] = $fields[$field_id]['value'];
    }
    return $data;
}

/**
 * Retrieves dealership entries matching the given manufacturer and location.
 *
 * @param int $form_id  The ID of the dealership form.
 * @param string $manufacturer  The manufacturer to match.
 * @param string $location  The location to match.
 * @param array $dealership_form_fields  An array mapping dealership form field names to their IDs
 * @return array  An array of matching dealership entries.
 */
function get_matching_dealerships($form_id, $manufacturer, $location, $dealership_form_fields) {
    $entries = wpforms()->entry->get_entries(
        array(
            'form_id' => $form_id,
            'field_id' => array(
                $dealership_form_fields['manufacturer'] => $manufacturer,
                $dealership_form_fields['location'] => $location
            )
        )
    );

    error_log('Matching dealerships query result: ' . print_r($entries, true));

    return $entries;
}

/**
 * Handles the scenario where no matching dealerships are found.
 *
 * @param array $customer_data An array of customer data
 * @param array $config Configuration settings
 */
function handle_no_matching_dealerships($customer_data, $config) {
    error_log('No matching dealerships found.');

    // Option 1: Send an email to the customer
    wp_mail(
        $customer_data['email'], 
        $config['no_match_email_subject'], 
        $config['no_match_message'], 
        array('Content-Type: text/html; charset=UTF-8')
    );

    // Option 2: Display a message on the form (requires additional WPForms configuration)
    add_filter('wpforms_process_filter', 'modify_confirmation_message', 10, 3);

    function modify_confirmation_message($confirmation, $form_data, $entry_id) {
        global $config; // Access the $config array from the outer scope
        if ($form_data['id'] == $config['customer_form_id']) {
            $confirmation['message'] = $config['no_match_message'];
            $confirmation['type'] = 'error'; // Or 'warning' if you prefer
        }
        return $confirmation;
    }
}

/**
 * Sends an email notification to a dealership.
 *
 * @param object $dealership  The dealership entry object
 * @param array $customer_data  An array of customer data
 * @param array $dealership_form_fields  An array mapping dealership form field names to their IDs
 * @param string $subject The email subject
 */
function send_email_to_dealership($dealership, $customer_data, $dealership_form_fields, $subject) {
    $to = $dealership->fields[$dealership_form_fields['email']]['value']; 
    $message = 'A new customer inquiry matches your dealership\'s criteria. Here are the details:';

    foreach ($customer_data as $key => $value) {
        $message .= "\n" . ucfirst(str_replace('_', ' ', $key)) . ": " . $value;
    }

    $headers = array('Content-Type: text/html; charset=UTF-8');

    if (wp_mail($to, $subject, $message, $headers)) {
        error_log('Email sent successfully to: ' . $to);
    } else {
        error_log('Failed to send email to: ' . $to);
    }
}

// Hook to process after WPForms submission
add_action('wpforms_process_complete', 'send_email_to_matching_dealerships', 10, 4);
				
			

The custom PHP code provided in this post offers a more elegant and efficient solution. It allows you to use a single WPForms form to capture customer inquiries and then dynamically match those inquiries with the appropriate dealerships based on criteria like location and manufacturer. Here’s how it works:

  1. Single Form: You create a single WPForms form to collect customer information, including their desired location and manufacturer preferences.
  2. Database Query: When a customer submits the form, the code queries your WordPress database to identify dealerships that match the customer’s criteria.
  3. Dynamic Email Notifications: The code then automatically sends email notifications to the matching dealerships, providing them with the customer’s contact information and inquiry details.

Benefits of Dynamic Dealership Matching

  • Simplified Form Management: You only need to maintain a single form, reducing complexity and streamlining your workflow.
  • Scalability: The code is designed to handle large datasets efficiently, making it suitable for businesses with hundreds or even thousands of clients.
  • Flexibility: You can easily add, remove, or modify dealerships in your database without having to update static email recipient lists.
  • Improved User Experience: Customers receive faster and more relevant responses from dealerships that are best suited to their needs.

Implementing the Solution

While the code provided in this post offers a solid foundation, you might need to customize it further to fit your specific WPForms setup and business requirements. Remember to replace the placeholders in the $config array with your actual WPForms form and field IDs. Also, consider implementing the “Option 2” for handling no matching dealerships if you want to display a message directly on the form, and make sure your WPForms confirmation settings allow for custom messages. Consider consulting with a WordPress developer or PHP expert to ensure proper implementation and integration.

Dynamic dealership matching can revolutionize your lead management process in WPForms. By leveraging custom code and the WPForms API, you can create a more efficient, scalable, and user-friendly system for connecting customers with the right dealerships. 

Shout out to:  itsyaku for sharing his original code request

If you’re ready to streamline your lead management in WPForms, consider implementing dynamic dealership matching. Contact a WordPress developer today to get started!