How the Friday Shorts posts come to be

I’m always looking for a way to automate things – whether it be in my work life, personal life, home life, or even my blog life – when I first started to do Friday Shorts, an initiative for me to share out some blogs and articles that sparked my interest it was a manual process.  There was a lot of “Who wrote that article again?, What site was that again?, Where’s that link I emailed?” going on in my head and even though it was only a handful of links it was still a lot of work.   Now I had already automated my sharing of links out to Twitter (needs an update BTW, oauth1 depreciated in Google Script now – another post) and for the most part I’ve found that the articles I chose for Friday Shorts are the same as the ones I share out.   So with all that said I set out to automate a process that would at the very least get a draft of a Friday Shorts article into this blog – and this is what I’ve come up with.

So in order to do this I’ve utilized four different services; Google Drive/Scripts, IFTTT, Delicious, and WordPress – each playing a key role in the automation.  So the process goes as follows

  • While perusing all the great blogs out there if I find one I feel needs to be included, I quickly use the Delicious toolbar button to create a public bookmark with the ‘FridayShorts’ tag.  Also, while using my RSS reader of choice (Digg) – if I ‘Digg’ a post, IFTTT runs a recipe to automatically create bookmarks of the post with the proper tag.
  • Another IFTTT recipe takes all of my Delicious ‘FridayShorts’ tagged bookmarks, and appends them to a Google Spreadsheet within my Drive account.
  • From there I have a WordPress plugin I’ve developed which essentially connects to a Google Script which parses a spreadsheet – allowing me to select which articles I’d like to include and finally creating a draft WordPress post (Friday Shorts) following a specific template.  The articles which I select are then updated (through the Google Script calls) in order to ensure they aren’t displayed the next time I go through the process.
  • I clean up the post, add some pictures, descriptions, links and whatever and publish it…

So with all that said let’s have a quick look at how each of the components are setup and configured.

IFTTT

If this then that is a great tool for automating almost anything within your life.  For the purposes of creating a Friday Shorts post I have two main recipes which are utilized…  In all honesty recipes on IFTTT are fairly simple to setup so I’ll simply just show the screenshots outlining what they do.

Digg to Delicious
Delicious to Google
DiggToDeliciousIFTTT DelciousToGoogleIFTTT

See – pretty simple to setup – at then end of it all we should be left with a spreadsheet similar to the following…

FridayShortsSpreadsheet

Google Script

Now we have the information that we want sitting inside a Google Spreadsheet – but before we get into the WordPress Plugin we first need to create a Google Script (script.google.com) containing all of the functions and methods which will actually do the work we request from WordPress.  To do so, go to script.google.com and select File-New Project.  This should open up a blank script for you to run with.

Sometimes it’s easier just to see the whole thing first so let’s just lay it out there for you – we can go through some specifics at the end of the script.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// open up the spreadsheet and set the active sheet.
var files = DriveApp.getFilesByName('FridayShortsLinkCollector');
var file;
while (files.hasNext()) 
{
file = files.next();
Logger.log(file.getName());
}
 
var ss = SpreadsheetApp.open(file);
var sheet = ss.getSheets()[0];
 
// return specific link
function getLink(articleid)
{
var values = sheet.getDataRange().getValues();
var articles = [];
for(var i=0, iLen=values.length; i<iLen; i++) 
{
if(values[i][6] == articleid) 
{
var article = [];
article.push(values[i][6].toString());
article.push(values[i][1].toString());
article.push(values[i][4].toString());
article.push(values[i][0].toString());
article.push(values[i][5].toString());
articles.push(article);
}
}
return articles;
}
 
// return all unprocessed links
function getAllLinks2()
{
var values = sheet.getDataRange().getValues();
var articles = [];
for(var i=0, iLen=values.length; i<iLen; i++) 
{
if(values[i][5] == "0") 
{
var article = [];
article.push(values[i][6].toString());
article.push(values[i][1].toString());
article.push(values[i][4].toString());
article.push(values[i][0].toString());
article.push(values[i][5].toString());
articles.push(article);
}
}
return articles;
}
 
// mark specific link as processed
function markArticleProcessed(articleid)
{
values = sheet.getDataRange().getValues();
 
for(var i=0, iLen=values.length; i<iLen; i++) 
{
if (values[i][6] == articleid)
{
values[i][5] = "1";
}
}
sheet.getDataRange().setValues(values);
}

So, if you are having trouble with my great comments throughout the code (I know, one-line here and there :)) let me try and explain a few things.  First of all, Lines 1 through 11 simply find the Spreadsheet within my Google Drive containing the links, then set the active sheet to the first one.

From there things are a bit more simple – the getLink() function returns an array of one specific article, taking in the articleID (auto genereated number in the spreadsheet) as a paramater.  The getAllLinks2() function returns an array of all of the articles within the spreadsheet (so long as their 5th cell (or processed as I call it) contains a value of 0.  The markArticleProcessed() function takes in a specific articleID as a parameter, and simply changes it’s 5th cell to a 1 – meaning it has been processed by a Friday Shorts article.

GoogleDeployAPIThat’s it for Google code but there are a few other things that you will need to do in order to make your script available for use by the WordPress plugin.  First off, select ‘Publish->Deploy as API executable”  Be sure to select “New” under the version (you will need to do this upon making any changes to the code) and make note of the API ID – we will need this for the PHP calls in WordPress.  Go ahead and click ‘Update’ when ready!

Secondly we need to open up some API’s within Google in order to allow the script to access your Google Drive content.  This is done in the developers console.  The easiest way I’ve found to get to the place we need to be is by selecting Resources->Developer Console Project.  If you haven’t already you will have to give your project a name and save it.  Once that is done simply click the link shown to go the scripts associated project.

DevelopersConsoleLink

The two APIs that we will need to open up for this project are the Drive API and the Google Apps Script Execution API (as shown below).  From the Dashboard select ‘Enable APIs and get credentials like keys”.  From there you should immidiately see the Drive API, but may have to search for the Script Execution API.  Either way, in the end you need to have them enabled as shown below…

APIsEnabled

From here move down to the Credentials section.  We need to create credentials to allow WordPress to access our Google content.  To do so select ‘New Credentials’ and then ‘Oauth Client ID’ as the type.  When presented with the application type chose ‘Web Application’, give it a name, and set the proper redirect URLs.  This can get tricky and will certainly change given your setup but my working setup is shown below.

redirectURIs

As you can see I’ve entered quite a few redirect URIs – not sure if I need them all but it works this way.  Also, make note of your Client ID and Secret – put it in the same place as your Script/API Id as we will need all of this for the WordPress Plugin.  For now, we are done with Google 🙂

The WordPress Plugin

I don’t want to go too deep into the specifics of how to create WordPress Plugins – partly because there is a lot too cover – too much for a this post, oh, and partly because I have no idea about 99% of it.  I simply fiddled until I got what I needed to work.  Again, let me simply just lay out some code and explain what it does – I’ll leave the fine details of the structure of WordPress Plugins to someone else.

folderstructure

As for my plugin there are really only 5 components to it..

  • The Google PHP SDK – download it here
  • fridayshorts.php – this is the main plugin page
  • fridayshorts-functions.php – this is a page containing all of the function calls to the Google Script
  • options.php – this page contains a means to setup the options for the plugin (the Script ID, Client ID and Client Secret)
  • js – some Javascript for checking boxes and stuff 🙂

Due to the fact that there is probably a few hundred lines of code within the plugin itself I’m not going to throw it all out there – instead I’ll just put up a few examples of how I call the Script Execution API from within the PHP code.

First up we need to import the PHP SDK for Google declare some variables – I’ve stored my client id and secret (from the Google section above) in a wordpress option – so to recall these we simply just need to do the following…

require_once 'Google/autoload.php';
 
$client_id = get_option('fsGoogleClientID');
$client_secret = get_option('fsGoogleClientSecret');
$redirect_uri = get_option('fsGoogleRedirectURI');

Now that we have this information we can start setting up the objects we need to interact with our Google script as shown below, storing everything we need in the client object.  As you can see I’ve also specified the scopes in which the API requests will fall under.

$scriptId = get_option('fsGoogleScriptID');
$client = new Google_Client();
$client->setApplicationName("Process Friday Shorts");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setScopes(array('https://www.googleapis.com/auth/drive','https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/spreadsheets'));
$client->setAccessType('offline'); // Gets us our refreshtoken

As far as processing one of the functions in the Google script that can be done as shown below.  I’ve also shown the code I use to display data on my plugin pages so you can sort of visualize what is happening.  The function getAllLinks is passwed through the setFunction function (alot of function in there :)) and you can see how I go about parsing the response back from the API call to build out an HTML table containing data from my spreadsheet.

function getAllLinks()
{
global $client,$scriptId;
$client->setAccessToken($_SESSION[‘token’]);
$service = new Google_Service_Script($client);
$request = new Google_Service_Script_ExecutionRequest();
$request->setFunction(‘getAllLinks’);
$response = $service->scripts->run($scriptId, $request);
$resp = $response->getResponse();
$articles = $resp[‘result’];

//build html table and return
$content = ‘<table width=”98%” bgcolor=”white”><TR><TD><input type=”checkbox” onchange=”fridayshorts_links_checkall(this)” name=”checkAll” value=”all”></TD><TD><B>Title</B></TD></TR>’;
foreach ($articles as $article)
{
$content .= ‘<TR><TD><input type=”checkbox” name=”art[]” value=”‘.$article.'”></TD><TD>’.$article.'</TD></TR>’;
}
$content .= ‘</TABLE>’;
return $content;

}

Anyways, enough with the php code – if you are in dire need of it just let me know and I’ll send it to you – way to boring to go through it all line by line.  In the end though I’m left with nice little GUI that allows me to select which items I’d like to include in my Friday Shorts post as shown below…

fridayshortsplugin

Once I’ve selected which posts I’d like to include within my new Friday Shorts post I can go ahead and click Create Draft.  What happens then is a new draft is created within WordPress in a format that I specified for my Friday Shorts posts.  The code to do so is as follows

$my_post = array(
'post_content' => $content,
'post_title' => "Friday Shorts",
'post_status' => 'draft',
'tags_input' => 'Friday Shorts'
);
$post_id = wp_insert_post( $my_post, true );

Additionaly, remember that markArticleProcessed function within our Google Script – it’s called as well, passing the parameter of each link as it loops over them and sending that id back to the Google Script using the setParameters function on the request object – as follows…

function markArticleProcessed($articleid)
{
global $client,$scriptId;
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Script($client);
$request = new Google_Service_Script_ExecutionRequest();
$request->setFunction('markArticleProcessed');
$request->setParameters($articleid);
$response = $service->scripts->run($scriptId, $request);
$resp = $response->getResponse();
$article = $resp['result'];
 
return;
 
}

So now you know just how far I will go in order to maintain my comfort level of laziness – honestly, automation is key in my life and anything I can automate means more time for creativity!  Again, I’m sorry I couldn’t go deeper into the PHP/Wordpress plugin development – it would just be one heaping pile of code on a page that makes no sense – but if you are interested definitely get in touch with me and I will send it along!  Anyways, thanks for reading thus far and I hope this post helps you in some way automate something of your own!