A Google+ Widget for WordPress

I looked for, but did not find, a reliable, easy to use, solid Google+ widget for WordPress. All I want to do is display on my WP blog a little sidebar listing of the 4 or 5 most recent activities from my G+ account.  Is that so hard?

Not sure why I couldn’t find it, but since I am interested, I looked into building a plugin. How hard could it be?  Turns out: not very.  You can see the results to the right.

Google is encouraging programmatic use of their social network.  They’ve published the network protocols – the HTTP request and response messages required to do various things. They also produced and released client-side libraries that implement these protocols – very nice. They’ve got one for PHP.   So, yeah, obviously, that seems like the right thing to use as a base for WordPress interaction with Google+ .

The “Hello World” of PHP-to-Google+ apps:

<?php 
$apiKey = "xxx-double-secret-xxxx";
$id = "101866550969463527083";

require_once 'src/apiClient.php';
require_once 'src/contrib/apiPlusService.php';

$client = new apiClient();
$client->setDeveloperKey($apiKey);
$plus = new apiPlusService($client);
$person = $plus->people->get($id);

echo "<h1>User info</h1><pre>\n";
print_r($person);
echo "</pre>\n<hr/>\n";

$collection = 'public';
$results = $plus->activities->listActivities($id, $collection);

echo "<h1>Activites</h1><pre>\n";
print_r($results);
echo "</pre>\n<hr/>\n";

echo "<h1>Comments</h1>\n<ul>\n";
foreach ($results['items'] as $item) {
    if ($item['verb'] == 'post' && is_array ($item['object'])) {
      print('<li>' . $item['object']['content'] . "</li>\n");
    }
}
echo "</ul>\n";

That worked pretty well, and took about 60 seconds of download and install. With that kind of momentum I went right into constructing my first wordpress plugin.   It’s a simple model – implement a class that extends WP_Widget .  Provide a widget() method that renders the thing. Inside the render function, include a subset of the code from the Hello, World app above. Ba da boom.

WordPress seems very nice to use, and very easy to extend.

This plugin is prety simplistic. It uses the API Key method, rather than OAuth2, for authentication to Google. It works just fine.  For a highly-loaded website, I’d need to insert some caching to eliminate unnecessary hits on the Google+ service. But for my nice and friendly blog, it’s just fine.

Here’s the code if anyone else wants to try it out.

 


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.