Publishing to WordPress via the REST API from R (with httr and JWT)

The WordPress REST API is awesome.

For a project I was working on this week I needed to be able to publish pages to WordPress via the API from R. Needless to say, there aren’t a ton of resources available online about how to do this (read: none). After fighting a losing battle between httr’s implementation of OAuth and the WordPress implementation of OAuth in Jetpack, I decided to try using JSON Web Tokens for authentication. That finally got things moving.

Here are the steps I took to get things up and working.

1. Create a throw away WordPress instance to work against. You don’t want to be experimenting with publishing and deleting posts on a blog you actually care about. Once you’ve figured everything out and have all the content published you want to publish, you can use Tools => Export to move the finished product to the blog you actually want the content to live on. (You should probably be doing this on Reclaim Hosting.)

2. Install the JWT Authentication for WP REST API plugin. As you follow the installation steps, make sure that the two lines you add to your .htaccess file come immediately below the RewriteEngine on directive. If you put them further down (e.g., below the WordPress directives) it will not work. Your .htaccess file will look like:

3. Install the httr library for R if you don’t already have it.

install.packages("httr")

4. You’re ready to go! Here’s the code I’m using to publish from within RStudio (you’ll need to change the URL and credentials to match your own):

Comments on this entry are closed.