Facebook plugin for wordpress

This week in the office we’ve been playing with the Facebook SDK and seeing what it can do, with a mind to using it on an upcoming project (that I can’t talk about!).  After a bit of playing, and bouncing ideas off each other we managed to get some fairly exciting stuff working.  Since I can’t publish the code we came up with, and I wanted to try out some other aspects of the SDK (well, multiple SDKs since theres Javascript and PHP variants to get your head around…) I thought I’d see how easy it was to create a plugin for wordpress.

If my boss is reading this by the way, I did pick up some directly applicable techniques and learning how to write plugins for various frameworks and applications is always useful….

Anyway, on to the code.  There was a lot of trial and error involved in this, so how it’s set out here is nothing like the actual development process, this is a much more cleaned up version!

 

the actual facebook code is fairly straightforward.  First we need to load the facebook javascript, and initialise it:

<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
FB.init({
            appId  : '    <?php echo $FB_APP_ID; ?>',
            status : true, // check login status
            cookie : true, // enable cookies to allow the server to access the session
            xfbml  : true  // parse XFBML
        });

You’ll notice a PHP variable echoed in there, that’s the facebook app id, which we set at the top of the code.  I’ll go into some detail about how to get this ID later, but for now all you need to know is that due to limitations of the Javascript API, there’s no way to create a web apoplication and distribute it with your app ID embedded in there already, everyone who uses your plugin or app or whatever has to create their own app on facebook so they have an APP ID to use.  This is really annoying, but it kind of makes sense… for web applications facebook locks down access to specified domains, so only requests coming from those domains get serviced by the API. I’ve no idea how this works for ‘Nativeish’ apps written using something like PhoneGap.  I assume they have some way round it, maybe they allow access from localhost or something.  Anyway, moving on…

Next we need to check whether we successfully logged into facebook.  For this we use the ‘FB.LoginStatus’ call, which returns an object with a status string to tell us whether we successfully logged in or not.  Here we also do some cookie shenanigans, to check whether this is the first time you’ve logged into the app (in effect, whether you’ve just installed the app), if so we post soemthing to the user’s wall to say ‘hey, look at this cool app I’ve just installed’ with a link back to tall-paul.co.uk to drive some traffic my way.

Finally, if we’re successfully logged in AND the ‘posttofacebook’ cookie is set, we do a post to facebook.  Some explanation is required here.  Because we want to use the javascript framework and the WordPress API is php (ie: serverside) the best way I’ve found of firing javascript actions attached to a wordpress ‘publish’ action is to set a cookie on the publish action, and then when the page refreshes after the action use the presence of the cookie to kick off the javascript we want to call.

FB.getLoginStatus(function(response) {
               if (response.status === 'connected') {    
                       facebook_app_authorised = true;
                    if (jQuery.cookie("tpfbpost") == "not authorised"){
                        //post to wall because we've just authorised for the first time
                        activationPost();                        
                    }               
                    if (jQuery.cookie("postTofaceBook") > -1){
                        <?php
                        $post_id = $_COOKIE['postTofaceBook'];
                        $my_post = get_post($post_id);
                        preg_match("/<p>(.*)<\/p>/",$my_post->post_content,$matches);
                        $description = strip_tags($matches[1]);
                        $site_name = get_bloginfo('name');
                        $thumb_id = get_post_thumbnail_id($post_id);
                        if ($thumb_id > -1){
                            $picture = wp_get_attachment_url($thumb_id);
                        } else {
                            $picture = "/wp-content/plugins/tallpaulfbpost/defaultimage.jpg";
                        }                        
                        ?>
                        link = "<?php echo get_permalink($post_id);?>";
                        message =  "A new article has been published on <?php echo $site_name;?>";
                        name = "<?php echo $my_post->post_title; ?>";
                        picture = "<?php echo $picture;?>";
                        description = "<?php echo $description;?>";
                        link = "<?php echo get_permalink($post_id);?>";
                        postToFaceBook(message,picture,link,name,description,"","postTofaceBook");                            
                    }     
                    addAuthorisedText();
                } else if (response.status === 'not_authorized') {
                    //set cookie so we know we're doing authorisation
                    jQuery.cookie("tpfbpost","not authorised");
                    addAuthoriseLink();
                } else {  
                    jQuery.cookie("tpfbpost","not authorised");      
                    addAuthoriseLink();
                }
            });

 

Finally we need to bind to the ‘publish_post’ action, and set our cookie to trigger off the facebook post when the page refreshes:

//set a cookie so we do a facebook post when the page reloads
function facebook_post_hook($post_id){
    setcookie("postTofaceBook",$post_id);
}

//hook into the publish post action
add_action('publish_post','facebook_post_hook',8)

There’s a lot more in there, but you can download the plugin and have a look at the finer details at the end of the article.

Now how to use the plugin?  First off you’ll need to download it and install it on your wordpress site like any other plugin.  Once you’ve done that head over to facebook and search for ‘developer’ in the top search bar.  That should take you to the lovely Developer app as shown below.  Click ‘create new app’ and fill in the required fields (see below for how the ‘Tall-paul.co.uk’ one is setup:

The only thing you really need to worry about are the ‘App domain’ and ‘Website’ fields.  These must match the domain / address of your wordpress blog or the plugin won’t work.  If you want to use it on multiple domains you’ll need a seperate facebook app for each domain.  Again, this isn’t my choice, it’s just how the facebook javascript API works.

Once that’s done copy the APP ID from the app page and paste it into ‘tallfbpost.php’  (replacing the current $FB_APP_ID) at the top of the file.

Now if you go to ‘Settings->writing’ in your wordpress control panel you should see a link at the bottom saying ‘click here to authorise the app’.  Click the link, accept the permissions and you’re done.

Publish a new post and you should see it appear on your facebook wall.

Future enhancements:

  • Add setting for app ID in the settings area
  • change behaviour so only newly published items are posted to facebook

Download (v0.1)




No Comments


You can leave the first : )



Leave a Reply

Your email address will not be published. Required fields are marked *