Menü schliessen
Created: September 20th 2024
Last updated: December 9th 2024
Categories: Advanced Custom Fields,  Php,  Wordpress
Author: Ian Walser

Efficient QR Code Generation in WordPress with PHP: A Comprehensive Guide for Developers and Admins

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Short introduction

In this post, we will walk you through how to generate dynamic QR codes in WordPress using PHP. Whether you're a beginner developer, Linux/Windows system admin, or tech-savvy professional, this guide will cover all the necessary steps to implement and customize a QR code generator for your WordPress website.

QR codes offer a practical way to share information such as contact details or links in a simple, scannable format. By using the phpqrcode library, we’ll demonstrate how to automate QR code generation for custom post types and integrate it seamlessly with WordPress’ ACF (Advanced Custom Fields) plugin.

Use Cases for QR Code Generation in WordPress

QR codes are valuable in many tech-oriented environments. Here are two common use cases where this solution can be highly beneficial:

  • Digital Business Cards for Sales Teams: Teams can share their contact details via QR codes generated automatically from vCard information stored in WordPress.
  • Internal Contact Sharing for Companies: Organizations can implement QR codes for internal team profiles, making it easier to share details within the company through scanning.

Installing and Configuring the phpqrcode Library

Before diving into the code, you'll need to install the phpqrcode library, which is essential for generating QR codes within WordPress. Here’s how you can set it up:

Step 1: Download the Library

You can download the phpqrcode library directly from SourceForge.

Step 2: Include the Library in Your WordPress Project

Once the library is installed, you need to include it in your WordPress project. Place the following line at the top of your PHP file where the QR code generation occurs:

require_once __DIR__ . '/path-to-phpqrcode-library/phpqrcode.php';

QR Code Generation Code Implementation

The code snippet below shows how to automatically generate a QR code when saving a post of the custom post type cpt-team-de in WordPress:


function generate_qr_code($post_id) {
    if (get_post_type($post_id) !== 'cpt-team-de') {
        return;
    }

    $values = get_fields($post_id);
    $name = $values['vcard_info']['name'] ?? '';

    if (empty($name)) {
        delete_old_qr_image($post_id);
        update_field('vcard_link', '', $post_id);
        return;
    }

    $upload_path = wp_upload_dir();
    $filename = get_qr_filename($name);
    $file_path = $upload_path['basedir'] . '/' . $filename . '.png';
    $url_path = $upload_path['baseurl'] . '/' . $filename . '.png';

    $qr_content = build_qr_content($values['vcard_info']);

    delete_old_qr_image($post_id);

    // Generate and save QR code
    QRcode::png($qr_content, $file_path);

    update_field('vcard_link', $url_path, $post_id);
}
add_action('save_post', 'generate_qr_code', 20);

This code will generate a unique QR code based on the vCard information fields, such as name, phone number, and email, and save it in the uploads directory. Each time a post is updated, the QR code will be refreshed.

Managing and Cleaning Up QR Codes

To avoid clutter and keep your file system clean, it’s essential to remove old QR codes when they're no longer needed. The following function helps manage this:


function delete_old_qr_image($post_id) {
    $upload_path = wp_upload_dir();
    $old_link = get_field('vcard_link', $post_id);
    $position = strpos($old_link, 'qrcodes/');
    $link_trimmed = substr($old_link, $position);
    $img_to_delete = $upload_path['basedir'] . '/' . $link_trimmed;
    if (file_exists($img_to_delete)) {
        unlink($img_to_delete);
    }
}

Comparison: Custom PHP QR Code Solution vs. API Solutions

While custom PHP QR code generation is highly flexible, it's worth comparing it to third-party APIs that provide similar functionality. Here's how the custom solution compares to the Google Chart API and QR Server:

Feature PHP Script Google Chart API QR Server
Customization High Moderate Low
Speed Fast (local) Moderate Fast
No External Dependency Yes No No

Rendering the QR Code in WordPress

After generating the QR code, rendering it on the front end is simple. Here's a snippet you can use to display the QR code on the post:

<?php
$filepath = wp_upload_dir()['basedir'] . '/' . get_qr_filename(get_fields()['vcard_info']['name'] ?? '404notfound') . '.png';
$fileurl = get_field('vcard_link');
if (!empty($fileurl) && file_exists($filepath)) {
    $title = get_the_title(). "QR Code";
    echo"<img src='{$fileurl}' alt='{$title}' />";
} ?>

This code checks if the QR code file exists before displaying it on the post. This ensures you only render valid QR codes to avoid broken image links.