Quick Start with Shortcode
Add this code to your theme's functions.php file to create a QR code shortcode:
functions.php
// Add to your theme's functions.php
function qr_code_shortcode($atts) {
$atts = shortcode_atts(array(
'data' => get_permalink(),
'size' => 200,
), $atts);
$api_key = get_option('qr_api_key');
$response = wp_remote_post('https://www.qrcodeapi.io/api/generate', array(
'headers' => array(
'Authorization' => 'Bearer ' . $api_key,
'Content-Type' => 'application/json',
),
'body' => json_encode(array(
'data' => $atts['data'],
'size' => (int) $atts['size'],
'format' => 'png',
)),
));
if (is_wp_error($response)) {
return '<p>Error generating QR code</p>';
}
$image = wp_remote_retrieve_body($response);
$base64 = base64_encode($image);
return '<img src="data:image/png;base64,' . $base64 . '" alt="QR Code" />';
}
add_shortcode('qrcode', 'qr_code_shortcode');
Usage
Use the shortcode in any post or page:
Shortcode Examples
<!-- QR code for current page URL -->
[qrcode]
<!-- QR code for custom URL -->
[qrcode data="https://example.com"]
<!-- QR code with custom size -->
[qrcode data="https://example.com" size="400"]
Settings Page
Add a settings page to store your API key:
Add Settings Page
// Add settings menu
function qr_api_settings_menu() {
add_options_page(
'QR Code API Settings',
'QR Code API',
'manage_options',
'qr-api-settings',
'qr_api_settings_page'
);
}
add_action('admin_menu', 'qr_api_settings_menu');
function qr_api_settings_page() {
if (isset($_POST['qr_api_key'])) {
update_option('qr_api_key', sanitize_text_field($_POST['qr_api_key']));
}
$api_key = get_option('qr_api_key', '');
?>
<div class="wrap">
<h1>QR Code API Settings</h1>
<form method="post">
<table class="form-table">
<tr>
<th>API Key</th>
<td><input type="text" name="qr_api_key" value="<?php echo esc_attr($api_key); ?>" class="regular-text" /></td>
</tr>
</table>
<?php submit_button(); ?>
</form>
</div>
<?php
}
Auto QR Codes for Posts
Automatically add a QR code to every post:
Auto-add to Posts
function auto_add_qr_to_content($content) {
if (is_single()) {
$qr = do_shortcode('[qrcode size="150"]');
$content .= '<div class="post-qr-code"><p>Scan to share:</p>' . $qr . '</div>';
}
return $content;
}
add_filter('the_content', 'auto_add_qr_to_content');
Ready to Add QR Codes to WordPress?
Get your free API key and start adding QR codes to your WordPress site.
Get Your Free API Key