WordPress is an absolutely powerful platform to publish content, but up till now it lacked the ability to publish and read content using a proper restful API. That is about to change. The new WP-API plugin is slated to be part of the WordPress core creating an easy access layer from a decoupled frontend.
And a mobile app is of course such a decoupled frontend!
This talk will show you how to leverage the power of the WordPress API to build an app in Appcelerator Titanium which uses Backbone.js as it's way of syncing. We'll go through the WP API basics, custom post types, proper API logic and offline strategies for your first app. Connecting the dots into Backbone.js is then a piece of cake!
20. YOU KNOW HOW TO CREATE A PLUGIN?
EXTENDING THE API
21. MY PLUGIN.PHP SETUP
<?php
/*
Plugin Name: MY JSON API
Plugin URI: https://www.a-wp-site.nl/
Description: JSON REST API EXTENSION
Version: 1.0
Author: JRDK
Author URI: http://jrdk.nl
*/
require_once('src/Bootstrap.php');
new Bootstrap();
22. WHEN TO TRIGGER YOUR CODE
public function __construct()
{
add_action('plugins_loaded', [$this, 'initServer'], 100);
}
public function initServer()
{
if (!defined('JSON_API_VERSION')) {
// return early if WP API does not exist
add_action('all_admin_notices', [$this, 'showError']);
return;
}
}
23. ADD YOUR OWN CUSTOM POST TYPE
public function initServer()
{
//...
add_action('wp_json_server_before_serve', [$this, 'initEndpoints']);
}
public function initEndpoints($wp_json_server)
{
$ad = new Advertisement($wp_json_server);
}
class Advertisement extends WP_JSON_CustomPostType
{
protected $base = '/advertisements';
protected $type = 'advertisement';
}
30. BACK TO THE PLUGIN SETUP
public function initServer()
{
if (!defined('JSON_API_VERSION') || !defined('REST_API_VERSION')) {
// return early if WP API versions do not exist
add_action('all_admin_notices', [$this, 'showError']);
return;
}
add_action('wp_json_server_before_serve', [$this, 'initEndpoints']);
add_filter('rest_url_prefix', [$this, 'changeApiBase']);
}
public function changeApiBase()
{
return 'api';
}
32. EXPOSE CUSTOM POST TYPE
public function initServer()
{
//...
add_action('init', [$this, 'updateExposure'], 12);
}
public function updateExposure()
{
global $wp_post_types;
$wp_post_types['advertisement']->show_in_rest = true;
$wp_post_types['advertisement']->rest_base = 'advertisement';
}
39. THAT’S IT… AGAIN
var post = Backbone.Model.extend({
urlRoot: '/api/wp/v2/posts'
});
var posts = Backbone.Collection.extend({
model: post,
url: '/api/wp/v2/posts'
});
var newPost = new post({
title: ‘test',
content_raw: ‘test'
});
newPost.save();