← All posts

Simpler QR Code with QRserver

· Tools, WordPress

First appeared on mobifreaks.com · Updated

On Mobifreaks we wanted a QR code next to every mobile template demo, so people could open it on their phone. Making one by hand for every post was too much work, so we looked for something like lorempixel: a service that returns an image based on the URL you request. That is how we found QRserver (now goQR.me).

One image tag

Pass the size and the text or URL to the API, and it returns a PNG. The service still works the same way, now over HTTPS:

<img
  src="https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=https%3A%2F%2Fmunawarahmed.com"
  width="300" height="300"
  alt="QR code linking to munawarahmed.com">
  • size is in pixels. Keep it square.
  • data is the text or URL to encode. URL-encode it, so characters like & and ? inside your link don't break the request.
  • The 2012 version of my snippet had a stray ; after the &, which broke the data parameter. The one above is fixed.

WordPress: one per post

Inside the loop, generate a code for each post's permalink:

<?php $qr = 'https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=' . rawurlencode( get_permalink() ); ?>
<img src="<?php echo esc_url( $qr ); ?>" width="300" height="300"
     alt="<?php echo esc_attr( 'QR code for ' . get_the_title() ); ?>">

My 2012 snippet put the_permalink() straight into the URL, with an extra quote that closed the src attribute early. rawurlencode() and esc_url() fix both problems.

When to generate it yourself

An external API is quick, but every visitor's browser sends the encoded URL to a third party, and your page depends on their uptime. If either matters, generate the code yourself:

  • At build time or on the server, with a library such as qrcode for Node.js or endroid/qr-code for PHP. Save the result as an image or inline SVG.
  • For a one-off, Chrome and Edge can create a QR code for the current page from their share menu.