Last active
December 10, 2015 20:38
-
-
Save mhawksey/4489090 to your computer and use it in GitHub Desktop.
WordPress Postviews Stats Analysis Google Apps Script. More info http://mashe.hawksey.info/2013/01/wordpress-postviews-stats
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment