Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
WordPress Postviews Stats Analysis Google Apps Script. More info
function wordpressStatPostviews(api_key, blog_uri, end, days, limit) {
// build url for api. Found better results using json rather than csv (csv didn't get years worth)
var url = ""+api_key+"&blog_uri="+blog_uri+"&end="+Utilities.formatDate(end, "GMT", "yyyy-MM-dd")+"&days="+days+"&limit="+limit+"&table=postviews&format=json";
var output = [["Link","Title","Title - Short","Date","Views"]]; // initialise return array
try {
var options = { "method" : "get" }; // initialise options for UrlFetchApp
var response = UrlFetchApp.fetch(url, options); // fetch url
if (response.getResponseCode() == 200) { // if response
var raw = Utilities.jsonParse(response.getContentText()); // parse text respose into json
raw.reverse(); // reorder to oldest first - no real need but helped with debugging
for (i in raw){ // data is returned as object per day so iterate across
var postdate = raw[i].date; // pull post date (as string) considered converting to date object but not required
for (j in raw[i].postviews){ // in each date object there is array of views per post, interate across to push into returned 2d array
var apost = raw[i].postviews[j]; // abreviating
// noticed a bug in returned data. Views for homepage have correct post_id but post_title is pulled from last interation
var title = apost.post_id === 0 ? "Homepage" : apost.post_title;
// creating a short title for published table (no cell wrapping)
var titleShort = title.length > 50 ? title.substring(0,50)+"..." : title;
// push row to output
output.push([blog_uri+"/?p="+apost.post_id,title, titleShort, postdate, apost.views]);
return output;
} catch(e) {
throw e;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment