Creating a QR Code Generator in Divi

Written by Dan Mossop

QR codes are an effective way to direct users to specific URLs quickly. By integrating a QR code generator into your Divi site, you can allow your users to generate their own QR codes and track how often the QR codes are scanned. In this post, we'll guide you through a demonstration of setting up a dynamic QR code generator and tracker in Divi, using the Divi QR Code Module.

Here's how it will look:

The QR code generator developed in this tutorial is for demonstration purposes only and shouldn't be used as-is without proper testing and security considerations. In particular, the demonstration code allows redirections to arbitrary URLs, which can present a security risk. It's crucial to implement proper validation and sanitization when using this in a production environment.

This setup involves a few key steps:

  1. Creating a form to input the URL
  2. Generating the QR code dynamically
  3. Tracking and displaying the number of scans

Here's how you can accomplish this.

Setting Up the Page

We'll create a two-column layout in Divi. On the left, we have a form for inputting the URL, and on the right, we display the generated QR code along with the scan statistics.

Left Column: URL Input Form

Add a Code Module to the left column and insert the following HTML for the form:

<form action="" method="get">
  <input type="url" name="url" placeholder="Enter QR Code URL"/>
  <input type="submit"/>
</form>

When users input a URL and submit the form, the QR code will be generated dynamically based on the provided URL.

Right Column: QR Code and Scan Statistics

In the right column, add the QR code module and a Text Module below it. In the Text Module, include the following shortcodes to display the scan statistics:

Scans this week: [qr_code_scans period="weekly"]

Total scans: [qr_code_scans]

Adding Functionality with PHP Code

Next we'll add several blocks of PHP code to handle QR code generation, redirection, and scan tracking. You can add these into the functions.php file of a child theme, or using a plugin such as Code Snippets.

Step 1: Update QR Code Data

We'll use a filter to update the code_data attribute of the QR code module based on the URL parameter. This step ensures that the QR code dynamically reflects the input URL.

// === Set the QR Code redirect URL from the query parameter ===

add_filter('et_pb_module_shortcode_attributes', 'update_qr_code_data', 10, 5);

function update_qr_code_data($props, $attrs, $render_slug, $_address, $content) {
	global $wp;
    if ('et_pb_dbqr_qr_code_module' === $render_slug) {
        $url = isset($_GET['url']) ? esc_url($_GET['url']) : '';

        if (!empty($url) && filter_var($url, FILTER_VALIDATE_URL)) {
            $current_page_url = home_url(add_query_arg(array(), $wp->request));
            $props['code_data'] = add_query_arg('redirect', urlencode($url), $current_page_url);
        }
    }
    return $props;
}

Step 2: Handle Redirection and Tracking

Next, we configure the redirection process and keep track of the scans. To reduce security risks associated with arbitrary redirections, we are using wp_safe_redirect instead of wp_redirect. This restricts the QR code URL redirections to pages on the current site. If you need to allow the QR code to point to any url, you can change wp_safe_redirect() to wp_redirect(), but please ensure you are aware of the security implications of doing so. 

// === Perform and track redirects (i.e. scans of the QR code) ===

add_action('template_redirect', 'handle_custom_redirect');

function handle_custom_redirect() {
    if (isset($_GET['redirect'])) {
        $redirect_url = esc_url_raw($_GET['redirect']);

        if (filter_var($redirect_url, FILTER_VALIDATE_URL)) {
            // Get the current page ID
            global $wp;
            $current_url = home_url($wp->request);
            $page = get_page_by_path($wp->request);
            $page_id = $page ? $page->ID : 0;

            if ($page_id) {
                // Get the current redirect count array
                $redirect_data = get_post_meta($page_id, '_redirect_data', true);
                $redirect_data = is_array($redirect_data) ? $redirect_data : array();

                // Create a hash for the redirect URL
                $url_hash = hash('sha256', $redirect_url);

                // Increment the count for this URL and store the timestamp
                if (!isset($redirect_data[$url_hash])) {
                    $redirect_data[$url_hash] = array('count' => 0, 'timestamps' => array());
                }

                $redirect_data[$url_hash]['count']++;
                $redirect_data[$url_hash]['timestamps'][] = current_time('timestamp');

                // Update the redirect data in post meta
                update_post_meta($page_id, '_redirect_data', $redirect_data);
            }

            // Perform the redirect
            wp_safe_redirect($redirect_url);
            exit;
        }
    }
}

Step 3: Display Scan Counts

Finally, we'll create a shortcode to display the scan counts. This shortcode can be configured to show either the total number of scans or the number of scans within the past calendar week.

// === Create shortcode to display current QR code's scan count ===

function display_qr_code_scans($atts) {
    global $wp;

    // Extract the 'period' attribute
    $attributes = shortcode_atts(
        array(
            'period' => 'total', // default value
        ),
        $atts
    );

    // Get current page information
    $current_url = home_url($wp->request);
    $page = get_page_by_path($wp->request);
    $page_id = $page ? $page->ID : 0;

    if ($page_id) {
        // Retrieve the redirect data array from post meta
        $redirect_data = get_post_meta($page_id, '_redirect_data', true);
        $redirect_data = is_array($redirect_data) ? $redirect_data : array();

        // Retrieve the 'redirect' URL parameter
        $redirect_url = isset($_GET['url']) ? $_GET['url'] : '';

        if (!empty($redirect_url)) {
            // Hash the redirect URL to match stored data
            $url_hash = hash('sha256', esc_url_raw($redirect_url));

            // Determine which value to return based on the 'period' attribute
            if ($attributes['period'] === 'weekly') {
                // Calculate the number of visits in the past calendar week
                $weekly_scan_count = 0;
                $one_week_ago = strtotime('-1 week');
                if (isset($redirect_data[$url_hash]['timestamps'])) {
                    foreach ($redirect_data[$url_hash]['timestamps'] as $timestamp) {
                        if ($timestamp >= $one_week_ago) {
                            $weekly_scan_count++;
                        }
                    }
                }
                return $weekly_scan_count;
            } else {
                // Get the total count for the hashed URL
                $total_scan_count = isset($redirect_data[$url_hash]['count']) ? intval($redirect_data[$url_hash]['count']) : 0;
                return $total_scan_count;
            }
        } else {
            return 0; // No data available
        }
    } else {
        return 0; // No data available
    }
}

add_shortcode('qr_code_scans', 'display_qr_code_scans');

Conclusion

By following these steps, you've created a dynamic QR code generator in Divi that not only generates QR codes based on user input but also tracks and displays the number of scans. Remember, this is a demonstration and shouldn't be used as-is without proper security considerations. 

For any further customization or questions, please feel free to reach out.

Simplify QR Code Integration on Your Divi Website

Effortlessly add customizable QR codes to your Divi pages with the Divi QR Code Module. Enhance user engagement and drive conversions by linking directly to offers, apps, or web pages. Match your site's design easily and connect with your audience like never before.

About Dan Mossop

Dan is a Scottish-born web developer, now living in Brisbane with his wife and son. He has been sharing tips and helping users with Divi since 2014. He created Divi Booster, the first Divi plugin, and continues to develop it along with 20+ other Divi plugins. Dan has a PhD in Computer Science, a background in web security and likes a lot of stuff, 

0 Comments

Submit a Comment

Comments are manually moderated and approved at the time they are answered. A preview is shown while pending but may disappear if your are cookies cleared - don't worry though, the comment is still in the queue.

Your email address will not be published. Required fields are marked *.

We may earn a commission when you visit links on our website.