WordPress REST API Quickstart

The WordPress REST API has been available since 4.7.  It’s robust, consistent, and nifty to work with. Why? Backend and mobile developers can use other frameworks while still keeping WordPress around for their customers. Frontend developers can build sites using JavaScript without having to touch PHP. Up is down, left is right, dogs and cats living together… Let’s get started!

Recommended Tools

Troubleshooting

  • JSON Formatter: CTRL/CMD+Click a triangle to collapse/expand nodes at the same level.
  • YARC: When testing with Basic Authentication, make sure you are logged out of WordPress first.

Getting Started

WP API supports all HTTP Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS.

WP API respects permissions but the developer must setup authentication separately.

Schema

WP API is self-documenting. Send an OPTIONS request to any endpoint and get back JSON Schema compatible info on how to use it:

OPTIONS

To get the entire API schema in a single query, add context=help at the index. (Ie. http://site/wp-json?context=help )

Features

WP API items have a _links node based on HAL (Hypertext Application Language):

_links

To reduce the number of HTTP requests use the _embed parameter to tell the API that the response should include embeddable resources.

_embed

WP API exposes pagination info in the response header.

Pagination

PHP to JSON

WP API renders JSON in a generic way that does not match the DB columns. Keep calm and RTFM:

if ( ! empty( $schema['properties']['author'] ) ) {
$data['author'] = (int) $post->post_author;
}
if ( ! empty( $schema['properties']['slug'] ) ) {
$data['slug'] = $post->post_name;
}
if ( ! empty( $schema['properties']['content'] ) ) {
$data['content'] = array(
'rendered'  => post_password_required( $post ) ? '' : apply_filters( 'the_content', $post->post_content ),
'protected' => (bool) $post->post_password,
);
}

{
"author": 1,
"slug": "chapter-1",
"content": {
"rendered": "<p>Hello World!</p>",
"protected": false
}
}

Example

Setup the Basic Authentication Plugin on your development environment.

In YARC, add your credentials:

YARC CredentialsSend an OPTIONS request to a post endpoint. The response will contain, among other information:

{
"methods": [
"POST",
"PUT",
"PATCH"
],
"title": {
"required": false,
"description": "The title for the object.",
"type": "object"
},

Translation: The API client can send a PUT request to change the title.

In YARC, send a PUT request with the following JSON to the endpoint:

{ 
"title": "My changed title!" 
}

Congratulations, you just changed the title. 

…cue the sound of a thousand keyboards furiously hacking.

Password Protect WordPress Admin With .htaccess

The wp-admin panel is already password protected in that you are required to login. Sometimes that’s not good enough. This tutorial explains how to add an additional layer of authentication to the login process, essentially blocking wp-login.php requests from annoying bots or other malicious users.

Step 1:

Create a `/path/to/.htpasswd` file. (More info.)

Step 2:

Create a `/path/to/your/site/wp-admin/.htacess` file with the following content:

AuthUserFile /path/to/.htpasswd
AuthType basic
AuthName "Restricted Resource"
require valid-user

# Whitelists

<Files "admin-ajax.php" >
   Order allow,deny
   Allow from all
   Satisfy any
</Files>

<Files "*.css" >
   Order allow,deny
   Allow from all
   Satisfy any
</Files>

<Files ~ "\.(jpg|jpeg|png|gif)$">
   Order deny,allow
   Allow from all
   Satisfy any
</Files>

Change `/path/to/` your files accordingly.

Important! Under Whitelists I have added entries for admin-ajax.php, *.css, and a regular expression for images. This unblocks WordPress’ AJAX functionality used by certain plugins, as well as CSS and image files certain themes may be importing. Without these you risk breaking your site.

Step 3:

Append the following to your existing WordPress .htaccess file one parent folder up (Ie. /path/to/your/site/.htaccess):

<Files wp-login.php>
  AuthUserFile /path/to/.htpasswd
  AuthType basic
  AuthName "Restricted Resource"
  require valid-user
</Files>

Change `/path/to/` your files accordingly.

WP Memcached Object Cache Leaks Memory?

While working on Pressbooks, a multi-site WordPress based web application, I noticed that some of our customers were getting blank pages in the admin section. Specifically, customers with a lot of Sites (or Books as they are known in Pressbooks).

Checking the error logs I saw that these customers were running out of memory.

PHP Fatal error:  Allowed memory size of 268435456 bytes exhausted (tried to allocate 292913 bytes) in /path/to/object-cache.php on line 212.

First, to temporarily stop the out-of-memory problem so I could profile I added the following to wp-config.php:

define( 'WP_MAX_MEMORY_LIMIT', '512M' );

Next, using Blackfire.IO I was able to determine the following:

Before
Before (285 MB)

That is, when a customer was looking at their dashboard, PHP was consuming 285MB of memory. Most of it the Memcached Object Cache plugin.

That’s weird. I’m using the latest version of the plugin, the plugin is developed by core developers, and no one has reported this before? Or so I thought! Browsing the plugin SVN I see the following change committed to trunk:

Changeset 626248

There’s a few more fixes in there as well. After installing the TRUNK version of this plugin Blackfire.IO displayed:

After
After (12.2MB)

That’s a 273MB improvement!

It took me days to figure out this problem. It would have saved me a lot of time had I seen the new code first.

Bonus info:

  • The code in TRUNK has at least 2 bugs. (…just load the file in PHPStorm and the errors will be underlined in red)
  • Redis Object Cache gives better results.

For now, this is good enough.