Build a Block Series - Part 6: QRCode
In this sixth screencast I get down to implementing the QRCode part of the block: loading the qrcode.js library and trigger it using the saved URL to create a QRCode.
Previous screencasts:
QRCode Implementation
In the cast, I alter the block's save function to output a div
we can target that includes the URL as a data attribute. The result is saving the following markup to the post content.
<div id="qrcode" data-url="https://mkaz.com/"></div>
Load QRCode Library
Next, we need to enqueue the qrcode.min.js
file to be loaded on the front-end. We do this by adding a standard WordPress enqueue, see Including CS & JavaScript documentation.
add_action( 'wp_enqueue_scripts', function() {
wp_enqueue_script( 'mkaz-qrcode-qrcodejs',
plugins_url( 'qrcode.min.js', __FILE__ )
);
});
Trigger QRCode
The final piece is triggering the qrcode library, this requires a new JavaScript file to load on the front-end, it adding another wp_enqueue_script
to the action above.
wp_enqueue_script( 'mkaz-qrcode-trigger',
plugins_url( 'qr-trigger.js', __FILE__ ),
array( 'mkaz-qrcode-qrcodejs' ),
filemtime( plugin_dir_path( __FILE__ ) . 'qr-trigger.js' ),
true // in footer
);
This loads a new file qr-trigger.js
that holds the plain old JavaScript to grab the element and trigger the code, referring to the example from the qrcode.js library.
// IIFE
(function () {
const elem = document.getElementById("qrcode");
const url = elem.dataset.url; // reads data-url
const qrcode = new QRCode(elem, {
text: url,
width: 256,
height: 256,
colorDark: "#000000",
colorLight: "#ffffff",
correctLevel: QRCode.CorrectLevel.H,
});
})();
A part you might not be familiar with is using IIFE syntax to wrap our JavaScript. IIFE stands for "Immediately invoked function expression". What IIFE does is create a safe space for our variables. It prevents conflicts with any other WordPress plugin that might load JavaScript and use the same variables names. Our variables are scoped inside our function, so no external conflicts. Read more about IIFE in the Scope Your Code document in the Block Editor Handbook.
Back to our block, with the trigger firing, when you load the page a QRCode shows. ðŸŒ
This was our goal for this part, still to come we need to add support for multiple blocks on a page, maybe some color and size customization.
Github Repo
Code is available at: https://github.com/mkaz/qrcode-block