The document provides an overview of a workshop on using the WordPress REST API and AngularJS. The workshop will cover REST API fundamentals, building custom REST APIs, unit testing APIs, and getting started with AngularJS by building controllers, templates, services, and factories. Attendees will learn through hands-on examples and code walkthroughs applied to real world projects.
3. CalderaLabs.org
Hi I'm Josh
Lead Developer: Caldera Labs
I make WordPress plugins
I teach about WordPress
I wrote a book about the WordPress REST API
I am a core contributor to WordPress
I am a member of The WP Crowd
4. CalderaLearn.com
Hi, I'm Roy
Senior Software Engineer:
The Walt Disney Company
I am a member of The WP Crowd
I blog on roysivan.com
I teach on Lynda.com & CalderaLearn
People say Hi to me a lot
5. What We're Covering Today
REST API 101
Building Custom REST APIs
Unit Testing Custom REST APIs
LUNCH BREAK
AngularJS (1.x) Basics
Building Decoupled Front-ends
Building Plugin Admin Screens
6. Educational Philosophy
All code is or is based on real world projects
We will show different ways of doing the same
thing.
Please ask why it's different
◇ we may give you a good answer
Stop us and ask questions
7. Structure For Today
foreach ( $sections as $section ) :
Concepts / Lecture
Example Code Walkthrough (you will be cloning locally)
Hands-on
DIY Group
Walk Through Code Group
endforeach;
8. WARNING
This workshop is to help you understand the basics
and some advanced technologies. Nothing will be
production ready code.
9. What you need for today
IDE or text editor (PHPStorm, Sublime, etc.)
Local WP install (VVV, DesktopServer, etc.)
npm
PHPUnit (optional, included in VVV)
Composer (optional)
AngularJS Batarang Chrome Extension
https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehid
hipcmcojjgiloacoafjmpfk?hl=en
13. “
CalderaLearn.com
The API allows you to take WP data and put it in a
bucket. What you do with that bucket is up to you.
-- Morten Rand Hendriksen
@mor10
15. API Powered Stuff
Things you can build that are powered by the API
Phone apps
Custom UI widgets on your site
Why use feed of another site, when you can API
Custom Dashboards in the admin
Custom WP Dashboard (YAS!)
User role based dashboard
39. Registering Route(s) : Field Sanitization Callback
Use to ensure data is safe.
Defined using a callable.
Change data to a safe value.
Return prepared value
40. Registering Route(s) : Field Validation Callback
Use to ensure data is correct.
Defined using a callable.
Used to reject invalid requests
Return true or false
41. Registering Route(s) : Field Validation Callback
public function validate_type( $value ){
if( !in_array( $value, [ 'big', 'small',
'very-small' ] ) ){
return false;
}
return true;
}
58. Unit Testing 101
Make Sure Things Return What They Should Return
$this->assertEquals( 42, function_that_returns_42() );
$this->assertSame( '42', function_that_returns_42() );
$this->assertArrayHasKey( 'roy', array( 'roy' => 'hi' ) );
Google: "Pippin Williamson Unit Tests for WordPress Plugins"
67. Unit Test Case For REST API Endpoints
Create a reusable class that:
Create Instance of WP_REST_Server
Boot routes
Make sure route is booted
68. Test Case Outline
class Test_API extends WP_UnitTestCase {
/** @var WP_REST_Server*/
protected $server;
protected $namespaced_route = 'caldera-forms/v1';
public function setUp() {}
public function test_register_route() {}
public function test_endpoints() {}
}
69. Test Case: Set Up
protected $server;
public function setUp() {
parent::setUp();
/** @var WP_REST_Server $wp_rest_server */
global $wp_rest_server;
$this->server = $wp_rest_server = new WP_REST_Server;
do_action( 'rest_api_init' );
}
70. Test Case: Test Route Is Registered
public function test_register_route() {
$routes = $this->server->get_routes();
$this->assertArrayHasKey( $this->namespaced_route,
$routes );
}
79. Not WordPress
To get you through the basics of
AngularJS we will be using
sample data, not WP
Our First Project
No npm or gulp
We aren’t using any build tools,
this is a pure sample
https://github.com/caldera-learn/angularjs-intro
80. Quicker & Easier
Quicker to get going to show
overall concepts.
Honest Truth
We already have a few projects
built in it that are ready to go
Why 1.x? 2 is in RC!
Roy is lazy
I am not lazy, but didn’t have
time to learn it deeply enough
yet to give a full workshop on it.
Josh Switched Teams
He used to be team NG1.
Now he is team VueJS.
81. HTML powered JavaScript
With Angular 1.x you can use
HTML to do most things reserved
for PHP.
Get the data using JS, template
with HTML. No PHP needed.
83. Setting up the app
All functionality lives within 1 app
We use ng-app to encapsulate the app in the DOM, it can be used on
any element including HTML.
Using it on the HTML encapsulates the whole DOM
84. Sample Data JSON
data.json
This file is going to be a sample of data, that we are going to use to build out
a simple Angular App, we will then replace it with the WordPress REST API
86. AngularJS Controllers
Controller is all about $scope
A Controller is defined by a JavaScript constructor function that is used to
augment the AngularJS Scope. When a Controller is attached to the DOM via
the ng-controller directive, AngularJS will instantiate a new Controller
object, using the specified Controller's constructor function
All new data to be used must be stored within $scope.your_key
ng-controller
90. First we must get data
$http is a jQuery AJAX wrapper & returns a promise
$http({method: ‘’, url: ‘’})
$http.get(url)
$http.post(url)
Because it returns a promise we use .then()
91. Say hello to JSON
JSON is the JavaScript Object Notation.
We display JSON with curly brackets
We work with JSON similar to PHP arrays
{{Object.key}} displays that key value
In PHP that would be $object[‘key’];
92. The loop HTML
<div ng-controller="listView">
<h2>Posts</h2>
<!-- Loop through $scope.posts -->
<article ng-repeat="post in posts">
<h2>{{post.title}}</h2>
</article>
</div>
93. Add more data
<article ng-repeat="post in posts">
<img ng-src="{{post.image}}" />
<h2>{{post.title}}</h2>
<div
class="post-content"
ng-bind-html="post.content | to_trusted">
</div>
</article>
95. Decoupled Front End
Decouple front end is a front end app that doesn’t live within
WordPress at all.
Your website: myawesomesite.com
Decoupled: myawesomeapp.com - but running on the same
data!
How cool is that!
96. Decoupled Use Cases
Phone App
Piece of functionality that communicates with WP data
Advanced, Unique UI
Combine with other APIs
Different Stack (decoupled app doesn’t need to be PHP)
97. Our decoupled App
npm
gulp
REST url that is publicly accessible (we will give you one)
Tacos, you always need tacos.
What you will need:
https://github.com/caldera-learn/decoupled-app
99. CORS
Allows browsers to make requests across
domains.
IS NOT SECURITY!!
By default WordPress REST API is same-origin
only.
Set at rest_pre_serve_request hook
104. AngularJS Factories
Factories allow you to create injectable objects.
Inject $resource into the factory it to create an object that can automatically handle REST calls.
app.factory('Posts',function($resource){
return $resource( ngWP.config.api + ‘/:post_type/:ID?per_page=:per_page’, {
post_type: 'posts',
ID:'@id',
per_page: ngWP.config.posts_per_page,
});
})
106. Local Storage
https://github.com/grevory/angular-local-storage
An AngularJS module that gives you access to the browser’s local storage with
cookie fallback.
Local storage is a key/value store which we call on. In our example the regular posts (blog) will check for
local storage first, before hitting the API.
107. UI-Router
https://github.com/angular-ui/ui-router
The Angular-UI project adds modules and functionality to Angular (think WP plugins for WP)
State Driven Routing
& a lot of other functionality we won’t need.
Shows its true power when you have 1 view within another (post.detail within post.list)
108. Templates
Separating out templates into templates directory
Cleaner code
Separation of views
1 controller can have 1 template
1 template can be powered by multiple controllers
Pure HTML (with JSON)
110. First thing is first
Clone the repo
You will need to run npm install and gulp
111. The config file
Create a file called config.js in /assets/js
var ngWP = ngWP || {};
ngWP.config = {
api: 'https://calderaforms.com/wp-json/',
posts_per_page: 5
// Not needed for our menu: 'app'
};
112. Stepping through the code
Main APP file
UI Router Definitions
Small controllers live here
Templates
Blog/Author List
Blog Detail
Product List
118. What’s Next?
Angular 2 Theme currently in development
github.com/royboy789/Angular-Wordpress-Theme/tree/v7
Vue.JS - The new simple JS framework
ReactJS - What everyone else wants you to learn
Admin Theme Boilerplate
github.com/WordPress-Admin-JavaScript-Boilerplate/ReactJS-Boilerplate
119. Want more Roy & Josh teachings?
Caldera Learn teaches through 4-week live classroom
style webinars. Teachers are Josh and/or Roy with future
guest teachers