Requirements
- A Displayr document.
- A WordPress website.
Method
1. Select Data Sources > Plus (+) > R.
2. Enter a name for the data set under Name.
3. Paste the below R code where it states Enter your R code here:
# GET request
library(httr)
site = GET("http://www.yoursite.com/wp-json/wp/v2/posts")
# Find max number of pages
tot = headers(site)$`x-wp-total`
maxPages = ceiling(as.numeric(tot)/100)
# Loop through all pages and return specified fields
dflist = list()
for (i in 1: maxPages) {
post = GET(paste0("http://www.yoursite.com/wp-json/wp/v2/posts?page=", i, "&per_page=100"))
data = content(post)
Date = sapply(data, function(x) return(x$date))
Date = lubridate::ymd_hms(Date) # Correctly format date
Title = sapply(data, function(x) return(x$title$rendered))
df = data.frame(Date, Title)
dflist[[i]] = df
}
posts = do.call(rbind, dflist)
- Note, you will need to replace www.yoursite.com with the name of your website, and you may need "https" rather than "http" depending on your setup.
- The code works out the maximum number of pages based on the total records, and then loops through each page to store this as a data frame within a list called dflist.
- In this example, we are returning the date and title of each blog post using the sapply method. The $ name within the function (i.e. date) corresponds to the WordPress API field name. See WordPress API Name References for details.
- Finally, we use the do.call command to combine all the rows of the list using rbind.
3. OPTIONAL: If you wish to make this call take place daily, you can add the below lines to the top of your R code:
library(flipTime)
UpdateEvery(1, "days", options = "wakeup")
4. OPTIONAL: You can test the R code first via Calculation > Custom Code until you have it working as this method allows for troubleshooting.