Build websites with R and WordPress

Note: The described setup was last tested in 2013 and probably requires changes to work with current versions of WordPress

Setup for WordPress

Install required R packages and WP plugins

For blogging from R to WP, I recommend:

  • SyntaxHighlighter plugin for WordPress for code boxes with R syntax highlighting
  • MathJax plugin for WordPress for nice math rendering using \(\LaTeX\) syntax
  • RWordPress R package for uploading posts from R to WP

You will need to build RWordPress yourself from its GitHub repository, using package remotes. RWordPress depends on the packages RCurl, XML, and XMLRPC. Note that XMLRPC is also only available from its GitHub repository. On Linux, all build tools should already be installed, on Windows, download Rtools<version>.exe and follow the instructions from Building R for Windows. Then build and install RWordPress:

Set up RWordPress with your login credentials and the site URL.

To make syntax highlighting work in WP with the SyntaxHighlighter plugin, R code should be enclosed in WP-shortcode instead of the knitr html output default <pre><code class="r">...</code></pre> like so:

[code lang='r']
...
[/code]

One option is to set up knitr itself to wrap code into WP-shortcode format. The downside to this option is that the output html is only usable within WP, but not as a standalone html page. Adapted from Carl Boettiger:

As an alternative, you can use the XML package to extract the html body produced by knitr and clean it to make it work for WordPress. Adapted with small modifications from William K. Morris:

Send the post from R to WordPress

In WP, you have to enable the “XML-RPC” option in Settings -> Writing -> Remote Publishing.

In R, first set the working directory to the one containing the html page. Then use newPost(..., publish=FALSE) to stage the post in WP as a draft to actually publish later from the dashboard. This uses knit2wp() as defined above:

If you plan to edit the post later and upload the changed html, save the return value from newPost(): It is the post id, necessary to identify the post using editPost().

For me, all this works fine, but I need to make sure the draft is opened first with the WP html editor, not the visual editor. So the html editor has to be “active”, i.e., was used last. After openening the draft with the html editor, I have to switch to the visual editor, and then hit “publish”. Publishing the post while still in the html editor does not work. Further switching between visual and html editor messes everything up.

Use knitr’s knit2wp() function

knitr now provides it’s own knit2wp() function that is similar to the one defined above. In addition, it also wraps the call to newPost(): see the knitr to WP example.

See also

Get the article source from GitHub

R markdown - markdown - R code - all posts