How to Capture a Marketing Lead Referral Source in Form Submissions with WordPress


In this tutorial, I'll show you how to capture the original referral source of your website visitors and store this information in a hidden field on form submissions using a simple WordPress plugin.

Plugin Overview

The plugin works by:

  • Tracking the referral source when a user visits the site.
  • Storing the referral source in the user's session.
  • Dynamically populating this referral source into hidden form fields on supported form builders like Gravity Forms and WPForms.

Getting Started: Setting Up the Referral Source Tracker Plugin

Step 1: Plugin PHP Code

Here’s the full PHP code for the plugin, which we'll go through step by step:

Referral Source Tracker - PHP
PHP
<?php
/*
Plugin Name: Referral Source Tracker
Description: Tracks the original referral source of a lead and adds it to form submissions.
Version: 1.1
Author: Mahmood Chowdhury
*/

// Hook to initialize tracking on page load
add_action('wp', 'referral_source_tracker_init');

function referral_source_tracker_init() {
    // Check if a referral source is already stored in the session
    if (!session_id()) {
        session_start();
    }

    // If the session doesn't have the source and the visitor is from an external site
    if (!isset($_SESSION['referral_source'])) {
        if (isset($_SERVER['HTTP_REFERER'])) {
            $referer = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST);

            // Source determination based on known platforms
            if (strpos($referer, 'google.com') !== false && strpos($referer, 'googleadservices.com') === false) {
                $_SESSION['referral_source'] = 'Google Search';
            } elseif (strpos($referer, 'bing.com') !== false && strpos($referer, 'bingads.microsoft.com') === false) {
                $_SESSION['referral_source'] = 'Bing Search';
            } elseif (strpos($referer, 'googleadservices.com') !== false) {
                $_SESSION['referral_source'] = 'Google Ads';
            } elseif (strpos($referer, 'bingads.microsoft.com') !== false) {
                $_SESSION['referral_source'] = 'Bing Ads';
            } elseif (strpos($referer, 'facebook.com') !== false) {
                $_SESSION['referral_source'] = 'Facebook';
            } elseif (strpos($referer, 'linkedin.com') !== false) {
                $_SESSION['referral_source'] = 'LinkedIn';
            } elseif (strpos($referer, 'capterra.com') !== false) {
                $_SESSION['referral_source'] = 'Capterra';
            } elseif (strpos($referer, 'g2.com') !== false) {
                $_SESSION['referral_source'] = 'G2';
            } elseif (strpos($referer, 'sourceforge.net') !== false) {
                $_SESSION['referral_source'] = 'SourceForge';
            } else {
                $_SESSION['referral_source'] = 'Direct or Other';
            }
        } else {
            // If no referer, assume direct or unknown traffic
            $_SESSION['referral_source'] = 'Direct or Other';
        }
    }
}

// Function to get the referral source dynamically
function get_referral_source() {
    if (!session_id()) {
        session_start();
    }
    return isset($_SESSION['referral_source']) ? $_SESSION['referral_source'] : 'Direct or Other';
}

// Make the referral source available as a dynamic variable in Gravity Forms and WPForms
add_filter('gform_field_value_referral_source', 'populate_referral_source');
add_filter('wpforms_field_value_referral_source', 'populate_referral_source');

function populate_referral_source($value) {
    return get_referral_source();
}

// Enqueue script to auto-populate hidden field in form
add_action('wp_enqueue_scripts', 'referral_source_enqueue_scripts');

function referral_source_enqueue_scripts() {
    wp_enqueue_script('referral-source-script', plugin_dir_url(__FILE__) . 'referral-source.js', array('jquery'), null, true);

    // Pass the referral source to JavaScript
    wp_localize_script('referral-source-script', 'referralSourceData', array(
        'referralSource' => get_referral_source()
    ));
}

Step 2: Understanding the PHP Code

1. Tracking the Referral Source:

  • The plugin hooks into the WordPress wp action, which runs after WordPress has loaded. It checks if a referral source is already stored in the user's session. If not, it extracts the HTTP_REFERER to determine where the user came from (Google, Bing, Facebook, etc.).
  • Depending on the source, the referral information is stored in a session variable ($_SESSION['referral_source']).

2. Retrieving the Referral Source:

  • The get_referral_source() function retrieves the referral source from the session. If it's not set, it defaults to "Direct or Other."

3. Populating the Referral Source in Forms:

  • The plugin supports Gravity Forms and WPForms. The referral source is dynamically added as a hidden field using the gform_field_value_referral_source and wpforms_field_value_referral_source filters.

4. Enqueueing JavaScript:

  • A JavaScript file (referral-source.js) is enqueued to pass the referral source to the front-end forms.

Step 3: JavaScript to Handle the Hidden Field

Now let’s write the referral-source.js file that will handle inserting the referral source into a hidden field.

Referral Source - JS
JavaScript
jQuery(document).ready(function($) {
    // Check if the hidden field for referral source exists
    var referralSourceField = $('input[name="referral_source"]');
    
    if (referralSourceField.length > 0) {
        // Populate the hidden field with the referral source value
        referralSourceField.val(referralSourceData.referralSource);
    }
});

Step 4: Adding the Hidden Field to Your Form

If you're using Gravity Forms or WPForms, you’ll need to add a hidden field to your form where the referral source will be stored. Here’s how:

  • Gravity Forms: Add a hidden field and set its default value to {referral_source}. This will automatically pull in the referral source tracked by the plugin.
  • WPForms: Add a hidden field and use the referral_source as the dynamic population value.

Step 5: Testing the Plugin

  1. Install the plugin by adding the PHP code to a new file in the /wp-content/plugins/ directory of your WordPress installation.
  2. Create a Gravity Form or WPForm with a hidden field for "Referral Source."
  3. Visit your website through different channels (e.g., Google, Facebook) and submit the form.
  4. Check the form entries to ensure that the correct referral source is captured.

With this custom plugin, you can track where your leads are coming from and automatically store that information in your form submissions. This is especially useful for optimizing marketing efforts and understanding which platforms are driving the most traffic to your website.

Feel free to download the plugin code from my GitHub repository and use it in your projects. You can find the code here.