WP JSON to Timeline JS

As part of some thoughts on building out a series of reflective views for student portfolio blogs, I thought seeing your WordPress posts in the TimelineJS view might be a useful way to look back over your progress.

I intend to wrap this into a custom spreadsheet template and/or a plugin1 but figured I’d sketch out how it works so far in case anyone was interested.

The WP Rest API makes it pretty easy to write the data via Google Script. I just want to cut out chunks of the data and put it in the right fields. The following script does that and writes it to a page named “wp.”

function getPosts() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('wp');
  
//get the data from the feed and get the last 50 items in this case (set via the URL)
  var url = 'https://bionicteaching.com/wp-json/wp/v2/posts?_embed&per_page=50';
  var response = UrlFetchApp.fetch(url); // get feed
  var json = response.getContentText(); // 
  var data = JSON.parse(json);
  //Logger.log(data);
  
  for (i = 0; i < data.length; i++){
    var ssData = [];    
    
    ssData.push(data[i].date.substring(0,4)); //post year   
    ssData.push(data[i].date.substring(5,7)); //post month   
    ssData.push(data[i].date.substring(8,10)); //post day   
    ssData.push(data[i].date.substring(11,19)); //post time 
  
    ssData.push(""); //filler for now for end date  info
    ssData.push("");
    ssData.push("");
    ssData.push("");
    ssData.push("");

    ssData.push(theUrl(data[i]) + data[i].title.rendered + '</a>'); //post title w link
    ssData.push(data[i].excerpt.rendered); //post excerpt
    
    ssData.push(featuredCheck(data[i])); //post feature image
    
    sheet.appendRow(ssData)[i];
  }
  
}

//have a featured image? then get it . . . 
function featuredCheck (data) {
  try {data._embedded['wp:featuredmedia'][0].media_details.sizes.full.source_url;
       return data._embedded['wp:featuredmedia'][0].media_details.sizes.full.source_url;
      } 
  catch (err){
    return "";
  }
   
}

//make things a bit neater by building the href via function
 function theUrl (data) {
   return '<a href="' + data.guid.rendered + '">'; //build the url 
 }


1 Or maybe just a page where you throw in a blog URL and get a bunch of alternate view/data options.

Comments on this post

No comments.

Leave a Reply

Trackbacks and Pingbacks on this post

No trackbacks.

TrackBack URL