QR Codes Shortcode on Your WordPress Site with Google API

If you want a simple and quick way to add QR codes to your WordPress site, you can use the Google Chart API to generate them on-the-fly. This tutorial will guide you through the process of creating a WordPress shortcode to generate a QR code for the current URL using Google’s Chart API.

Step 1: Create Your Shortcode Function

Add the following code to your theme’s functions.php file or in a custom plugin, or better yet, use a Code Snippets plugin for a safer way to add custom code.

function google_qr_code_shortcode($atts) { // Get the current URL $current_url = urlencode(get_permalink()); // Set default attributes for the shortcode $atts = shortcode_atts( array( 'size' => '150x150', 'alt' => 'QR Code', ), $atts, 'google_qr_code' ); // Construct the Google API URL for the QR Code $src = 'https://chart.googleapis.com/chart?cht=qr&chs=' . esc_attr($atts['size']) . '&chl=' . $current_url; // Return the QR Code Image return '<img src="' . esc_url($src) . '" alt="' . esc_attr($atts['alt']) . '" width="' . esc_attr($atts['size']) . '" height="' . esc_attr($atts['size']) . '">'; } add_shortcode('google_qr_code', 'google_qr_code_shortcode');

Step 2: Use the Shortcode

You can use the shortcode [google_qr_code] to generate a QR code for the current post or page. You can also pass parameters like size to customize it:

[google_qr_code size="200x200"]

This shortcode will generate a QR code that, when scanned, directs users to the page where the shortcode is placed.

Step 3: Styling Your QR Code

You might want to add some custom styles to ensure your QR code looks good on your site. Here’s a simple example:

img.google-qr-code { display: block; margin: 10px auto; border: 5px solid #fff; /* Adds a simple white border */ }

Conclusion

QR codes are an efficient way to connect your online content with offline marketing materials. With this simple shortcode, you can dynamically generate QR codes for any page of your WordPress website, leveraging the ease and power of Google’s Chart API. Just remember that since the API is deprecated, it might not be a long-term solution, and you may want to consider other QR code generation methods for future-proofing.