public
Last active

WordPress Postviews Stats Analysis Google Apps Script. More info http://mashe.hawksey.info/2013/01/wordpress-postviews-stats

  • Download Gist
gistfile1.js
JavaScript
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
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 = "http://stats.wordpress.com/csv.php?api_key="+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;
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.