Sie sind auf Seite 1von 15

WordPress By The Numbers

WordPress By The Numbers

WordPress By The Numbers

WordPress: By The Numbers.


Chapter 1: Building your rst Plugin

WordPress By The Numbers

What to expect from this chapter: Introduction to class based plugins for WordPress Version 1 of our plugin, that connects to Instagr.am and returns an auth token. The Wonder Twins of WordPress are the theme system and the plugin system. By leveraging these two powerful systems you can make WP do just about anything. Every release we see more and more functionality added to both areas, but as their power grows, so does their complexity. I have found that the best way to get your head around the complexity that we nd in these systems is to nd a concrete problem that we all will face at one time or another while working with WP, and craft a solution. Learn by doing, as it were. In the next couple of chapters we will be building out a fairly complex plugin, one that combines API consumption and caching. We will be hitting the Instagram API, authenticating and getting our latest photos, that we will then cache locally. As always the code in this chapter should have been delivered along with the chapter, and if you have any questions or you are stuck on something you can hit the forums for this chapter and receive help from your fellow readers, or from me. Lets get into it. To begin things off, here is the code for the plugin as it will sit at the end of this chapter. Dont worry if this is all greek to you, I will be explaining things as we go along.

WordPress By The Numbers

<?php /** * @plugin Instagram_Includimator * @version 0.1 */ /* Plugin Name: Instagr.am Includimator Plugin URI: http://chrisjdavis.org/btn/chapter-1/ plugin-code Description: With Instagr.am Includimator you can includimate your Instagr.am photos into your WordPress powered site. Author: Chris J. Davis Version: 0.1 Author URI: http://chrisjdavis.org License: GPLv2 or later */ class Instagram_Includimator { const INSTA_VERSION = '0.1'; const RESPONSE_CODE_PARAM = 'token'; const CACHE = '3600'; private $_endpointUrls = array( 'authorize' => 'https://api.instagram.com/ oauth/authorize/?client_id=%s&redirect_uri= %s&response_type=%s', 'access_token' => 'https://api.instagram.com/ oauth/access_token', ); private $_oauthToken = null; private $_accessToken = null; private function _setOauthToken( $user_id ) {
5

WordPress By The Numbers

$this->_oauthToken = get_user_option ( 'instagram_token' ); } public function openAuthorizationUrl() { $insta_plugin_url = plugin_dir_url( __FILE__ ); $params = array( 'client_id' => 'your_client_id', 'client_secret' => 'your_client_secret', 'grant_type' => 'authorization_code', 'redirect_uri' => $insta_plugin_url. '/ instagram_template.php', ); $authorizationUrl = sprintf( $this>_endpointUrls['authorize'], $params['client_id'], $params['redirect_uri'], self::RESPONSE_CODE_PARAM ); wp_redirect( $authorizationUrl ); exit( 1 ); } } ?> Alright now that we have that out of the way, lets take a look at this code, piece by piece.

Hello Instagr.am
First things rst, we need to go to Instagr.am and create a dev account for our plugin. To begin, you must login to the Instagr.am site: https://instagram.com/accounts/edit/

WordPress By The Numbers

This will redirect you to the login page, if you arent already logged in. Once that is over, head on over to the dev site: http://instagram.com/developer/ Here you will be able to create a new entry for your app. Go ahead and do that, taking note of the Client ID and Client Secret. The callback URL will need to be: http://yoursiteurl.com/wp-content/plugins/instagram/callback.php Once this has been done, its time to do some hacking!

The Process
So, before we write the rst line of code we need to understand what the lifecycle of our plugin is going to be. For this plugin, we need to accomplish the following: Allow the user to authenticate to Instagr.am Capture the token returned by Instagr.am Save the token to our database so it can be accessed later Request data associated with the token we have saved Cache data to speed up our site, and respect Instagr.ams TOS.

In this chapter we are going to cover creating the code that will allow us to authenticate with Instagr.am, and capture the token that is returned. This plugin will be a class based, PHP 5 laden joint, so strap yourselves in. Instagr.am uses oAuth for their API security. Explaining oAuth is beyond the scope of this chapter; you can nd many ne tutorials and explanations about it on the interwebs. Google, as always, is your friend.

WordPress By The Numbers

I nd the best teacher is to write code, so lets jump into the plugin. Dont worry I will be explaining things as we go and as always you can hit the forum for this chapter on the By The Numbers site. Every WP plugin begins the same way, with the same opening movement, or preamble if you will. Yeah, I am a music and history geek. Sue me. So here we go. What follows are best practices as I have decided. As always your mileage may vary. The bottom line is that you should follow whatever practices make sense to you, and make your life easier as a plugin developer.

/** * @plugin Instagram_Includimator * @version 0.1 */ /* Plugin Name: Instagr.am Includimator Plugin URI: http://chrisjdavis.org/btn/chapter-1/ plugin-code Description: With Instagr.am Includimator you can includimate your Instagr.am photos into your WordPress powered site. Author: Chris J. Davis Version: 0.1 Author URI: http://chrisjdavis.org License: GPLv2 or later */

This bit of code is how WP determines that this is indeed a plugin, as well as what information to list on the plugins page. Pretty simple really. Now lets get into the interesting bits.

WordPress By The Numbers

class Instagram_Includimator { const INSTA_VERSION = '0.1'; const RESPONSE_CODE_PARAM = 'token'; const CACHE = '3600';

So, rst we have dened a constant for our version, useful later on when we want to check for updates, or if we needed to run an migration/upgrade routine. Next we have created a constant for the type of response we want to get back from Instagr.am and nally we created a constant for the time to live for our cache. We wont be using that constant in this chapter, but it is good to have around none the less. Next we need to create some private variables and functions. private $_endpointUrls = array( 'authorize' => 'https://api.instagram.com/ oauth/authorize/?client_id=%s&redirect_uri= %s&response_type=%s', 'access_token' => 'https://api.instagram.com/ oauth/access_token', ); private $_oauthToken = null; private $_accessToken = null; private function _setOauthToken( $user_id ) { $this->_oauthToken = get_user_option ( 'instagram_token' ); }

WordPress By The Numbers

Right, so for those of you who are not familiar with this type of code, let me explain a bit.

Its all about being seen baby


There are 3 types of visibility in PHP. These are public, protected or private. Class members (functions, variables, etc) that are public can be accessed everywhere while members that are protected can be accessed only within the class itself or by inherited and parent classes. Members that are private can only be accessed by the class that contains the method or variable. So in a nutshell: If something is public you can call it anywhere, from in the plugin you are writing, from another plugin or from a theme le. If something is protected you can call it from the plugin you are writing, a plugin that extends the one you are writing, or by a parent plugin that your current plugin is built on top of. Finally if something is private, it can only be accessed from within the plugin you are writing, period. In our WP travels we will be using public and private mostly, but it is good to understand the differences between all 3. Since we will be needed to authenticate with an external site that will then send us back to a specied location, it is good to have info like this at hand. And speaking of accessing an external site, we might nd it useful to have a method for that in our class dont you think?

10

WordPress By The Numbers

Now we get into the good stuff. Crafting the URL we will use to make our call out to Instagr.am, and the code we need to process the data that is returned. Lets do this! First, the AuthorizationUrl function. public function openAuthorizationUrl() { $insta_plugin_url = plugin_dir_url( __FILE__ ); $params = array( 'client_id' => 'your_client_id', 'client_secret' => 'your_client_secret', 'grant_type' => 'authorization_code', 'redirect_uri' => $insta_plugin_url . '/ instagram_template.php', ); $authorizationUrl = sprintf( $this>_endpointUrls['authorize'], $params['client_id'], $params['redirect_uri'], self::RESPONSE_CODE_PARAM ); wp_redirect( $authorizationUrl ); exit( 1 ); } } At this point, our plugin is nished. Lets take a minute to unpack what is going on in this function shall we? First we are creating an array of parameters what we will combine to create the URL we will pass to Instagr.am to obtain our token. The PHP function sprintf() takes the collection of bits we give it, and cobbles them together into a web appropriate URL. We then call

11

WordPress By The Numbers

wp_redirect() so that the user is sent to the URL we just constructed with sprintf(), and exit to stop script execution. So at this point, we have the code necessary to create the URL, and send a user to the Instagr.am site to be authenticated. We still need to capture the token that is returned, and we need a place to send our user to for the whole process to start. To accomplish these tasks, we need to create two template les: send_off.php This is the le we will send our users to, so that we can start the authentication process. callback.php This is the le that our users will be returned to once they have authed and given us permission to access their data. First up is the send_off template.

Time for some templates


The rst step for our user is to load a page on their site that redirects them to Instagr.am to login and authorize our app. This page is fairly simple, it only really requires one function call to get the party started. <?php if ( is_user_logged_in() ) { $instagram = new Instagram_Includimator(); $instagram->openAuthorizationUrl(); } else { echo 'You must be logged into WordPress to enable Instagr.am integration'; } ?>

12

WordPress By The Numbers

When this page is loaded in a browser by our user, they will be swept off to Instagr.am to login and authenticate our app, if they are logged in. Pretty easy. Now that we have our template for send off, we need a template that will welcome our users back home with open arms. For that we need callback. Instagr.am will send us back a URL something like this: http://yoururl.com/wp-content/plugins/instagram/ callback.php#123456.578re78.fhjsd From the pound sign (#) on is what is referred to as a fragment. This fragment contains our token. We need to get at the token, but unfortunately PHP doesnt see the fragment, it is a client layer element. This means that the server doesnt process it, so we have to grab our old friend javascript to take care of this bit by breaking apart the URL, grabbing the fragment, and then redirecting to our page again, this time with a URL parameter that PHP can get to, ?fragment. <?php require( '../../../wp-load.php' ); ?> <?php get_header(); ?> <script> var parts = location.href.split('='); var bits = location.href.split('#'); if(parts.length > 1) { var params = parts[0].split('?'); var mark = '?'; if(params.length > 1) { mark = '?'; } if( bits[1] ) {
13

WordPress By The Numbers

location.href = bits[0] + mark + 'fragment=' + parts[1]; } } </script> <div id="container"> <div id="content" role="main"> <?php $user = wp_get_current_user(); if ( is_user_logged_in() ) { update_usermeta( $user_id, 'instagram_token', $_GET ['fragment'] ); ?> <div class="column post_holder"> <p>Thanks, your Instagram info has been saved, <a href="<?php bloginfo('url'); ?>" tite="Go Home">click here to return to the homepage</a>.</p> <?php echo 'Your auth token is: ' . $_GET ['fragment']; ?> <?php } ?> </div> </div> <?php get_footer(); ?> At this point you should be redirected to the same page, but this time with a URL like: http://yoururl.com/wp-content/plugins/instagram/callback.php? fragment=123456.578re78.fhjsd This URL can be processed by PHP, so all that is left is to grab the token from the URL via $_GET and save it to the DB. At this point you should now have working code that gets us past authentication and authorization. In our next chapter we will add methods to

14

WordPress By The Numbers

the plugin that will allow us to grab photos from Instagr.am and display them on our site. If you have any questions or problems with the code, feel free to stop by the forum for this chapter which can be found at: http://chrisjdavis.org/btn/forums/discussion/1/chapter-1 Thanks and happy hacking!

15

Das könnte Ihnen auch gefallen