How to Write A QR Code Generator Plugin

qr

In this article, I’ll show you how to write a plugin that will create QR code image for every post and page with wp_remote_get.

General Ideas

#1, Add QR image to post and page only.
#2, When plugin activated, it should create a folder to store QR image.
#3, Before generating QR image, it needs to check if we’ve created one for the particular post/page.
#4, Save QR image to folder.

Q&A about details

Q: How to generate QR image? What php library? or third party API?
A: Google provides an API for creating QR. Here is the sample URL: http://chart.apis.google.com/chart?chs=250×250&cht=qr&chl=http://www.test.com

Q: How to avoid duplicated QR image for same post.
A: Two solutions:
#1, store QR image URL in post custom field.
#2, use some hashing functions to generate a unique code for post URL and use the code as file name.

Note: I’m gonna use #2 solution and use md5 as hashing function. But actually MD5 has had some collisions.

Understanding Source Code

define(WPPD_QR_DIR,WP_CONTENT_DIR.'/wppdqr');
define(WPPD_QR_URL,WP_CONTENT_URL.'/wppdqr');
register_activation_hook(__FILE__, 'wppd_install');

function wppd_install(){
	if(!file_exists(WPPD_QR_DIR))
		wp_mkdir_p( WPPD_QR_DIR );
}

First of all, I define two constants and create a folder for storing QR images when activation.

add_action( 'the_content', 'wppd_add_qr_to_content');

function wppd_add_qr_to_content($content){
	if(!i_single()&&!is_page())
	       return false;
	$url = wppd_get_post_url();
	if($qr = wppd_get_qr($url))
		$content.= '<img src="'.$qr.'" />';
	return $content;

}

function wppd_get_post_url(){
	global $post;
	$post->filter = 'sample';
	return get_permalink( $post );
}

I hook to the_content action and add QR at the bottom of the content.

I apply a trick in wppd_get_post_url that set the filter of $post to sample. get_permalink’s only param should be post ID. With this trick, get_permalink will simply use $post instead of retrieving a new post with post ID. I find out this trick when I got stuck at exporting 100k+ post links.


function wppd_get_qr($url){
	if($existing_qr = wppd_get_existing_qr($url))
		return $existing_qr;
	return wppd_generate_qr($url);

}

function wppd_get_filename($url){
	return WPPD_QR_DIR.'/'.md5($url).'.png';
}

function wppd_get_existing_qr($url){
	$filename = wppd_get_filename($url);
	if(file_exists($filename))
		return WPPD_QR_URL.'/'.basename($filename);
	return false;
}

function wppd_generate_qr($url){
	$api_url = 'http://chart.apis.google.com/chart?chs=250x250&cht=qr&chl='.urlencode($url);

	$args = array(
			'timeout'=>'30'
			'blocking' => true,
                        'headers' => array('User-Agent'=>'set your user agent here'),
			'stream'=>true,
			'filename'=>wppd_get_filename($url),
			);

	$response = wp_remote_get($api_url,$args);

	if(200 != wp_remote_retrieve_response_code( $response ) )
		return false;

	return wppd_get_existing_qr($url);
}

wp_remote_get supports 10 plus arguments but I only list a few of them here because I think they are more important.

timeout, it is self-explanatory.
blocking, When set to false, it’ll execute the request but won’t return the response.
headers, set user agent, content type, cookies etc,. in this argument.
stream, when true, the response will be saved as file.
filename, use it along with stream.

Although wp_remote_get has cookies argument, I would recommend setting cookies directly in headers since the cookies should be represented using WP_Http_Cookie. As a lazy developer, I choose the simpler way. :]

wp_remote_retrieve_response_code is a utility function for handling response. The others are wp_remote_retrieve_headers, wp_remote_retrieve_header, wp_remote_retrieve_response_message, wp_remote_retrieve_body.

You can view the completed code at https://gist.github.com/wppd/4958366

Conclusion

I was gonna write an article about cURL alternatives in wordpress, but in the end, this article turned out to be a tutorial on how to write a QR code generator plugin…

Share and Enjoy

    FacebookTwitterGoogle PlusLinkedInStumbleUponPinterestRedditTumblrDiggEmailPrint

Related Posts