Post from RStudio to WordPress

By | 2016-11-20

Load Worpress with R

Welcome to my blogging effort.

Since this is the first post and a big part of the blog will be about workflows, I thought a description of my R -> WordPress flow might be a good introduction.

Up to now using a blog as documentation platform was just too time consuming. Doing it this way is turning out to be fun.

TechStack

Local Machine

In the cloud

Set up the environment

Before we start coding let's get everything together.

Create a directory structure

I like to use the directory structure as part of the workflow. You can create your structure either with:

  • Git Bash (as part of version control)
  • RStudio (when you create a new project)
  • or to keep things simple for now use the operating system utilities.

Create a directory that will be your blog working directory, in my case I use Blog and it is under my User directory. Anywhere will be OK as long as you can find it again. And stay away from the Program Files directories.

Create sub directories under the Blog directory namely:
1. figure
2. image
3. Pages
4. Posts
5. Templates

Image 1

Plots done by R wil end up in figure, images to upload will be placed in image, blog pages will be stored in Pages, posts (like this one) will be placed in Posts and Templates is for later use. The driver script and login credentials will be placed in Blog

Start RStudio

Create a new Project (File > New Project) and depending on how you decided to set up your directory structure create a New Directory or select an Existing Directory.

Load the necessary packages in R

  • pacman (R package management tool)
  • knitr
  • markdown
  • devtools
  • RCurl
  • XML
  • XMLRPC
  • RWordPress

RWordPress depends on the packages RCurl, XML, and XMLRPC, make sure you install these packages before you install RWordPress.

if (!require("pacman")) install.packages("pacman")

pacman::p_install(knitr, markdown, RCurl, devtools, XML)
pacman::p_install_gh(c("duncantl/XMLRPC"))
pacman::p_install_gh(c("duncantl/RWordPress"))

All the packages are available on CRAN, the last two can be found on Github.

Scripts

The description and code in
the post might not be the latest version. You are welcome to download the material from my Bitbucket Repositories.

Let's see what we are trying to achieve:

Image 2

User Credentials

The first script will keep the login credentials. It should only change again if your credentials change. My suggestion will be to create an user in WordPress with the necessary Roles and Capabilities (depending on how you want to utilize your blog).

Type or copy the following script (using your details) and save it in the Blog directory as login_credentials.R . The reason for having an external script is to make life easier when using version control. You can include it in the driver script if you want to.

# Rename to login_credentials.R

# Fill in YOUR Username, Password and blog_url.
Login = c(Username = 'Password')
WPUrl = 'blog_url/xmlrpc.php'

Driver Program

As the name implies this will be where the work is done. I also assume you have set up the environment as in the previous step.

Type or copy the following program and save it in the Blog directory as upload_post.R.

This program will grow as I use WordPress.

# upload_post.R

# Install RWordpress
library(RWordPress)
library(knitr)

# Next we make some choices on how we want our script to behave.

# post_name: Path and filename to be uploaded to WordPress
# post_title: Title to appear on WordPress
# post_categories: Vector with the categories we want to store
# post_keywords: Vector with the keywords
# post_publish: Set to FALSE if you want to check everything first in WordPress
# post_images: Create a list of all the images used in the post, then link them to images you want to upload.
# post_toc: If you want to create a Table of Contents based on your markdown script make it TRUE
# post_RPlots: If your R script creates plots you want to upload select TRUE.

# The images used are set up in the list below.
# Important is to set up the members in the vector as follows:
# 1 - the value you will use in the post to place the image
# 2 - the image location on the disk (in my setup it is the image directory)
# 3 - the alternative text that will created in the final html document

###############################################################################
post_name <- 'Posts/driver_test.Rmd'
post_title <- 'Upload Driver Test'
post_categories <- c('Workflow', 'R', 'WordPress')
post_keywords <- c('knitr', 'RWordpress')
post_publish <- FALSE
post_images <- list(img1 = c('img1','image/test_img1.jpg', 'Image 1'),
img2 = c('img2','image/test_img2.jpg', 'Image 2'))
post_toc <- TRUE
post_RPlots <- FALSE
###############################################################################

# Set up the credentials we created earlier.
source('login_credentials.R')
options(WordPressLogin = Login, WordPressURL = WPUrl)

# Include toc?  
if(post_toc){
library(markdown)
options(markdown.HTML.options =  c(markdownHTMLOptions(default = T),"toc"))
}

# Upload plots?
if(post_RPlots){
opts_knit$set(upload.fun = function(file){library(RWordPress);uploadFile(file)$url;})
}

# Convert the list to a data frame. Upload to WordPress and store the return value 
# for use in the next step
df <- as.data.frame(post_images, stringsAsFactors = FALSE)
tdf <- as.data.frame(t(df), stringsAsFactors = FALSE)
colnames(tdf) <- c("Chunk", "Image", "AltText")
tdf$url <- "Error"
for(i in 1:nrow(tdf)){
cat("Uploading", tdf$Chunk[i], "from", tdf$Image[i] , "\n")
tmp <- RWordPress::uploadFile(tdf[i,2], overwrite = FALSE)
tdf$url[i] <- tmp$url
tmp <- NULL
}

# Create the temporary file that will be used to create the HTML code. Ensure that the temporary file
# is create in the same directory your .Rmd document resides. In this case it is the Posts subdirectory

tdf$Chunk <- paste("## @knitr", tdf$Chunk)
tdf$url <- paste0("writeLines(sprintf(\"![%s](%s)\",\"",tdf$AltText, "\",\"" ,tdf$url, "\"))\n")
tdf$Image <- NULL
tdf$AltText <- NULL
write.table(tdf, file="Posts/tmp_knitr.R", quote = FALSE, sep = "\n", row.names = FALSE, col.names = FALSE)

# Post new entry to the wordpress blog and store the post id.
postid <- knit2wp(post_name , title = post_title, categories = post_categories, mt_keywords = post_keywords,
  publish = post_publish)

The Markdown document

Biggest thing of note here is that I use the external file created by the Driver program to place the images in the post. So make sure that the image names(first member in the vector) corresponds in both the driver and the Post.

Instead of duplicating this post I've just done a small example, you can get the full document on (http://bitbucket.org/marejp/quantowlblog/src).

 ---
title: "Driver Test"
author: "Johan Mare"
date: "Thursday, November 17, 2016"
output: html_document
---

# Test the driver program.

The Table of Contents above is generated in the *upload_post.R* code. You decide if you want it.

This post will be uploaded as my first post and will change as I'm testing the driver program.

## Text
To create documents here a basic knowledge of the following are essential:
- [Markdown](http://daringfireball.net/projects/markdown/),
- [knitr](http://yihui.name/knitr/).

## Images
For images I use external R code in knitr and R markdown. A description can be found on the 
[knitr](http://yihui.name/knitr/) site. Another brilliant description can be found at [ZevRoss](http://zevross.com/blog/2014/07/09/making-use-of-external-r-code-in-knitr-and-r-markdown/). While you are there
check out some of his other posts as well.

Use the following steps in your post to import the images:

### Load the external code 
The echo=FALSE will cause that nothing will be seen in the output, but the external code will be read.

```{r echo=FALSE}
read_chunk('tmp_knitr.R')
```

### Load the first image
```{r img1, results='asis', echo=FALSE}

```
Proudly produced by myself.

### Load the next image
```{r img2, results-'asis',echo=FALSE}

```

You can load as many images as you like, as long as they are declared in *upload_post.R*. Standardizing on **img** with a number works for me. 

Good luck

The end result of this script can be viewed here.

Final Step

All that is left now is the testing.

Run the Driver Program, log on to WordPress and check if the post and images are there. Preview and publish.

Conclusion

I believe this is an easy enough way to blog without wasting time jumping between applications.

There is place for improvement.

Sources

Books

Dynamic Documents with R and knitr, Second Edition (Chapman & Hall/CRC The R Series)

One thought on “Post from RStudio to WordPress

Leave a Reply

Your email address will not be published. Required fields are marked *