btn chapter 1

Upload: chris-j-davis

Post on 07-Apr-2018

236 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 Btn Chapter 1

    1/15

    WordPress By The Numbers

    1

  • 8/6/2019 Btn Chapter 1

    2/15

    WordPress By The Numbers

    2

  • 8/6/2019 Btn Chapter 1

    3/15

    WordPress: By The Numbers.

    Chapter 1: Building your first Plugin

    WordPress By The Numbers

    3

  • 8/6/2019 Btn Chapter 1

    4/15

    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 pluginsystem. By leveraging these two powerful systems you can make WP do

    just about anything. Every release we see more and more functionalityadded 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 thatwe find in these systems is to find a concrete problem that we all will face atone time or another while working with WP, and craft a solution. Learn bydoing, 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 theInstagram API, authenticating and getting our latest photos, that we willthen 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 somethingyou can hit the forums for this chapter and receive help from your fellowreaders, 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 thingsas we go along.

    WordPress By The Numbers

    4

  • 8/6/2019 Btn Chapter 1

    5/15

  • 8/6/2019 Btn Chapter 1

    6/15

    $this->_oauthToken= get_user_option

    ( 'instagram_token' );}publicfunctionopenAuthorizationUrl() {

    $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 first, we need to go to Instagr.am and create a dev account forour plugin. To begin, you must login to the Instagr.am site:

    https://instagram.com/accounts/edit/

    WordPress By The Numbers

    6

    https://instagram.com/accounts/edit/https://instagram.com/accounts/edit/https://instagram.com/accounts/edit/https://instagram.com/accounts/edit/
  • 8/6/2019 Btn Chapter 1

    7/15

    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 dothat, taking note of the Client ID and Client Secret. The callback URL willneed 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 first line of code we need to understand what thelifecycle of our plugin is going to be. For this plugin, we need to accomplishthe 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. Thisplugin 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 thescope of this chapter; you can find many fine tutorials and explanationsabout it on the interwebs. Google, as always, is your friend.

    WordPress By The Numbers

    7

    http://instagram.com/developer/http://instagram.com/developer/http://instagram.com/developer/
  • 8/6/2019 Btn Chapter 1

    8/15

    I find 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 theforum 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 followwhatever practices make sense to you, and make your life easier as aplugin developer.

    /**

    * @plugin Instagram_Includimator* @version0.1*//*Plugin Name: Instagr.am IncludimatorPlugin URI: http://chrisjdavis.org/btn/chapter-1/plugin-code

    Description: With Instagr.am Includimator you canincludimate your Instagr.am photos into your WordPresspowered site.Author: Chris J. DavisVersion: 0.1Author URI: http://chrisjdavis.orgLicense: GPLv2 or later

    */

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

    WordPress By The Numbers

    8

    http://chrisjdavis.org/http://chrisjdavis.org/btn/chapter-1/plugin-codehttp://chrisjdavis.org/btn/chapter-1/plugin-codehttp://chrisjdavis.org/http://chrisjdavis.org/http://chrisjdavis.org/btn/chapter-1/plugin-codehttp://chrisjdavis.org/btn/chapter-1/plugin-codehttp://chrisjdavis.org/btn/chapter-1/plugin-codehttp://chrisjdavis.org/btn/chapter-1/plugin-code
  • 8/6/2019 Btn Chapter 1

    9/15

    classInstagram_Includimator{ constINSTA_VERSION = '0.1'; constRESPONSE_CODE_PARAM = 'token'; constCACHE = '3600';

    So, first we have defined a constant for our version, useful later on when wewant to check for updates, or if we needed to run an migration/upgraderoutine. Next we have created a constant for the type of response we wantto get back from Instagr.am and finally we created a constant for the time tolive for our cache. We wont be using that constant in this chapter, but it isgood 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;

    privatefunction_setOauthToken( $user_id ) { $this->_oauthToken= get_user_option( 'instagram_token' );

    }

    WordPress By The Numbers

    9

    https://api.instagram.com/oauth/access_token'https://api.instagram.com/oauth/access_token'https://api.instagram.com/oauth/access_token'http://livepage.apple.com/http://livepage.apple.com/https://api.instagram.com/oauth/access_token'https://api.instagram.com/oauth/access_token'https://api.instagram.com/oauth/access_token'https://api.instagram.com/oauth/access_token'http://livepage.apple.com/http://livepage.apple.com/http://livepage.apple.com/http://livepage.apple.com/http://livepage.apple.com/http://livepage.apple.com/
  • 8/6/2019 Btn Chapter 1

    10/15

    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 accessedeverywhere while members that are protected can be accessed only withinthe class itself or by inherited and parent classes. Members that are privatecan 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 youare writing, from another plugin or from a theme file.

    If something is protected you can call it from the plugin you arewriting, a plugin that extends the one you are writing, or by a parentplugin that your current plugin is built on top of.

    Finally if something is private, it can only be accessed from within theplugin you are writing, period.

    In our WP travels we will be using public and private mostly, but it is good tounderstand the differences between all 3.

    Since we will be needed to authenticate with an external site that will thensend us back to a specified location, it is good to have info like this at hand.And speaking of accessing an external site, we might find it useful to have amethod for that in our class dont you think?

    WordPress By The Numbers

    10

  • 8/6/2019 Btn Chapter 1

    11/15

    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 isreturned. Lets do this!

    First, the AuthorizationUrl function.

    publicfunctionopenAuthorizationUrl() {

    $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 finished. Lets take a minute to unpack what isgoing on in this function shall we?

    First we are creating an array of parameters what we will combine to createthe URL we will pass to Instagr.am to obtain our token.

    The PHP function sprintf() takes the collection of bits we give it, andcobbles them together into a web appropriate URL. We then call

    WordPress By The Numbers

    11

  • 8/6/2019 Btn Chapter 1

    12/15

    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 auser to the Instagr.am site to be authenticated. We still need to capture thetoken that is returned, and we need a place to send our user to for thewhole process to start.

    To accomplish these tasks, we need to create two template files:

    send_off.php This is the file we will send our users to, so that wecan start the authentication process.

    callback.php This is the file that our users will be returned to oncethey have authed and given us permission to access their data.

    First up is the send_off template.

    Time for some templates

    The first step for our user is to load a page on their site that redirects themto Instagr.am to login and authorize our app. This page is fairly simple, itonly really requires one function call to get the party started.

    WordPress By The Numbers

    12

  • 8/6/2019 Btn Chapter 1

    13/15

    When this page is loaded in a browser by our user, they will be swept off toInstagr.am to login and authenticate our app, if they are logged in. Prettyeasy.

    Now that we have our template for send off, we need a template that willwelcome 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. Thisfragment 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 oldfriend javascript to take care of this bit by breaking apart the URL, grabbingthe fragment, and then redirecting to our page again, this time with a URLparameter that PHP can get to, ?fragment.

    varparts = 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] ) {

    WordPress By The Numbers

    13

    http://yoururl.com/wp-content/plugins/instagram/callback.php#http://yoururl.com/wp-content/plugins/instagram/callback.php#http://yoururl.com/wp-content/plugins/instagram/callback.php#http://yoururl.com/wp-content/plugins/instagram/callback.php#http://yoururl.com/wp-content/plugins/instagram/callback.php#http://yoururl.com/wp-content/plugins/instagram/callback.php#http://yoururl.com/wp-content/plugins/instagram/callback.php#http://yoururl.com/wp-content/plugins/instagram/callback.php#http://yoururl.com/wp-content/plugins/instagram/callback.php#http://yoururl.com/wp-content/plugins/instagram/callback.php#http://yoururl.com/wp-content/plugins/instagram/callback.php#http://yoururl.com/wp-content/plugins/instagram/callback.php#
  • 8/6/2019 Btn Chapter 1

    14/15

    location.href= bits[0] + mark +'fragment='+

    parts[1];}}

    Thanks, your Instagram info has been saved,

    At this point you should be redirected to the same page, but this time with aURL 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 tokenfrom the URL via $_GET and save it to the DB.

    At this point you should now have working code that gets us pastauthentication and authorization. In our next chapter we will add methods to

    WordPress By The Numbers

    14

    http://yoururl.com/wp-content/plugins/instagram/callback.php?fragment=http://yoururl.com/wp-content/plugins/instagram/callback.php?fragment=http://yoururl.com/wp-content/plugins/instagram/callback.php?fragment=http://yoururl.com/wp-content/plugins/instagram/callback.php?fragment=http://yoururl.com/wp-content/plugins/instagram/callback.php?fragment=http://yoururl.com/wp-content/plugins/instagram/callback.php?fragment=http://yoururl.com/wp-content/plugins/instagram/callback.php?fragment=
  • 8/6/2019 Btn Chapter 1

    15/15

    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 theforum for this chapter which can be found at:

    http://chrisjdavis.org/btn/forums/discussion/1/chapter-1

    Thanks and happy hacking!

    WordPress By The Numbers

    15

    http://chrisjdavis.org/btn/forums/chapter-one/http://chrisjdavis.org/btn/forums/chapter-one/