SlideShare a Scribd company logo
Extending The
WordPress REST
API
Josh Pollock
Hi, I'm Josh
Slides: JoshPress.net/extending-rest-api-talk
What We Are Covering
Extending The Default
Responses
v2.wp-api.
org/extending/modifyi
Creating Your Own
Endpoints
v2.wp-api.
org/extending/adding/
We're Skipping To The Back of The Book:)
Download: wpeng.in/wp-api-ebook/
Let's Talk About Defaults
Why Extend The Defaults?
Are endpoints of a default endpoint close, but
missing a field?
Combine POST requests.
add_filter( 'the_content', function( $content ) { …
add_filter( 'template_includes', function( $template ) { ...
Why Make Your Own?
● Unique data sets -- custom queries, custom
tables, wrapping existing classes.
● Just the data you need.
● Replace admin-ajax
$query = new WP_Query( $args );
$collection = new my_class( $params );
global $wpdb;
add_rewrite_rule('^leaf/([0-9]+)/?', 'index.php?page_id=$matches[1]', 'top');
Anatomy Of A REST Request
WP_REST_SERVER ??WP_REST_Request WP_REST_Response
Extending Defaults
Customizing Default Routes
● Add fields to response
○ Custom field or any other data
● Applies to all read and/or write endpoints of
route.
Meet register_api_field()
http://v2.wp-api.org/extending/modifying/
● Adds fields to one or more response
● Arguments:
○ Object (post type name or "terms", "meta", "user" or
"comments" )
○ Name of field
○ Args
■ Read Callback
■ Write Callback
■ Schema Callback
Example Handlers
function slug_get_meta_field( $object, $field_name, $request ) {
return get_post_meta( $object[ 'id' ], $field_name );
}
public function slug_update_meta( $value, $object, $field_name ) {
if ( ! $value || ! is_string( $value ) ) {
return;
}
return update_post_meta( $object->ID, $field_name, strip_tags(
$value ) );
}
Example Registration
add_action( 'rest_api_init', 'slug_register_spaceship' );
function slug_register_spaceship() {
register_api_field( 'post',
'starship',
array(
'get_callback' => slug_get_meta_field,
'update_callback' => slug_update_meta_field,
'schema' => null,
)
);
}
Adding Your Own Endpoints
Anatomy Of A REST Request
WP_REST_SERVER Your RouteWP_REST_Request WP_REST_Response
Request -> Callback -> Response
Check Permission Validate Fields Sanitize Fields
Callback
Response
Meet register_rest_route()
http://v2.wp-api.org/extending/adding/
Adds a collection of routes.
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/author/(?
P<id>d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
) );
} );
Namespacing & Versioning
register_rest_route() Defines
● Endpoints For Route
● Permissions for endpoints
● Transport methods for endpoints
● Fields for endpoints
● Callback for endpoints
● Schema
Endpoint URL
public function the_route() {
register_rest_route( 'swp_api', '/search',
array( )
);
}
Namespace
Route
Transport Method
public function the_route() {
register_rest_route( 'swp_api', '/search',
array(
'methods' => WP_REST_Server::READABLE,
)
);
}
GET
Permissions
public function the_route() {
register_rest_route( 'swp_api', '/search',
array(
'methods' => WP_REST_Server::READABLE,
'permission_callback' => array( $this, 'permissions_check' )
)
);
}
Permissions
public function permissions_check( $request ) {
$allowed = apply_filters( 'cwp_swp_api_allow_query', true, $request );
return (bool) $allowed;
}
public function permissions_check( $request ) {
return current_user_can( 'something' );
}
Standard WordPress Permissions/ Authentication!!!!!!!!!
Fields
public function the_route() {
register_rest_route( 'swp_api', '/search',
array(
'methods' => WP_REST_Server::READABLE,
'permission_callback' => array( $this, 'permissions_check' ),
'args' => $this->the_args(),
)
);
}
Fields
$args = array(
's' => array(
'default' => '',
'sanitize_callback' => 'sanitize_text_field',
),
'engine' => array(
'default' => 'default',
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => array( $this, 'validate_engine' ),
),
'page' => array(
'default' => 1,
'sanitize_callback' => 'absint',
),
);
Callback
public function the_route() {
register_rest_route( 'swp_api', '/search',
array(
'methods' => WP_REST_Server::READABLE,
'permission_callback' => array( $this, 'permissions_check' ),
'args' => $this->the_args(),
'callback' => array( $this, 'callback' ),
)
);
}
Callback
public function callback( $request ) {
$params = $request->get_params();
$cb_class = new class_that_does_something( $params );
$results = $cb_class->get_results();
if( is_array( $results ) {
return rest_ensure_response( $results, 200 );
}elseif( is_wp_error( $results ) ) {
return rest_ensure_response( $results, 500 );
}else{
return rest_ensure_response( __( 'FAIL!', 'text-domain' ), 500 );
}
}
Response
Should be either:
● An instance of WP_REST_Response
● An instance of WP_Error
rest_ensure_response( $data, $code, $headers );
You're Ready To Learn More
JoshPress.net/extending-rest-api-talk
wpeng.in/wp-api-ebook/
That's About It
JoshPress.net
CalderaWP.com
@Josh412
Josh Pollock

More Related Content

What's hot

Inside Bokete: Web Application with Mojolicious and others
Inside Bokete:  Web Application with Mojolicious and othersInside Bokete:  Web Application with Mojolicious and others
Inside Bokete: Web Application with Mojolicious and others
Yusuke Wada
 
Undercover Pods / WP Functions
Undercover Pods / WP FunctionsUndercover Pods / WP Functions
Undercover Pods / WP Functions
podsframework
 
Introduction to the Pods JSON API
Introduction to the Pods JSON APIIntroduction to the Pods JSON API
Introduction to the Pods JSON API
podsframework
 
Head First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & ApplicationHead First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & ApplicationJace Ju
 
Getting to The Loop - London Wordpress Meetup July 28th
Getting to The Loop - London Wordpress Meetup  July 28thGetting to The Loop - London Wordpress Meetup  July 28th
Getting to The Loop - London Wordpress Meetup July 28th
Chris Adams
 
Zend framework
Zend frameworkZend framework
Zend framework
Prem Shankar
 
Developing apps using Perl
Developing apps using PerlDeveloping apps using Perl
Developing apps using Perl
Anatoly Sharifulin
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
postrational
 
Keeping it small - Getting to know the Slim PHP micro framework
Keeping it small - Getting to know the Slim PHP micro frameworkKeeping it small - Getting to know the Slim PHP micro framework
Keeping it small - Getting to know the Slim PHP micro framework
Jeremy Kendall
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
vvaswani
 
Mojolicious - A new hope
Mojolicious - A new hopeMojolicious - A new hope
Mojolicious - A new hope
Marcus Ramberg
 
What happens in laravel 4 bootstraping
What happens in laravel 4 bootstrapingWhat happens in laravel 4 bootstraping
What happens in laravel 4 bootstraping
Jace Ju
 
Introduction to AJAX In WordPress
Introduction to AJAX In WordPressIntroduction to AJAX In WordPress
Introduction to AJAX In WordPress
Caldera Labs
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsMichael Peacock
 
Keeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkKeeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkJeremy Kendall
 
Dance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech TalkDance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech TalkMichael Peacock
 
Codeigniter : Using Third Party Components - Zend Framework Components
Codeigniter : Using Third Party Components - Zend Framework ComponentsCodeigniter : Using Third Party Components - Zend Framework Components
Codeigniter : Using Third Party Components - Zend Framework Components
Abdul Malik Ikhsan
 
An introduction to Laravel Passport
An introduction to Laravel PassportAn introduction to Laravel Passport
An introduction to Laravel Passport
Michael Peacock
 
How to migrate Cakephp 1.x to 2.x
How to migrate Cakephp 1.x to 2.xHow to migrate Cakephp 1.x to 2.x
How to migrate Cakephp 1.x to 2.x
Andolasoft Inc
 

What's hot (20)

Inside Bokete: Web Application with Mojolicious and others
Inside Bokete:  Web Application with Mojolicious and othersInside Bokete:  Web Application with Mojolicious and others
Inside Bokete: Web Application with Mojolicious and others
 
Undercover Pods / WP Functions
Undercover Pods / WP FunctionsUndercover Pods / WP Functions
Undercover Pods / WP Functions
 
Phinx talk
Phinx talkPhinx talk
Phinx talk
 
Introduction to the Pods JSON API
Introduction to the Pods JSON APIIntroduction to the Pods JSON API
Introduction to the Pods JSON API
 
Head First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & ApplicationHead First Zend Framework - Part 1 Project & Application
Head First Zend Framework - Part 1 Project & Application
 
Getting to The Loop - London Wordpress Meetup July 28th
Getting to The Loop - London Wordpress Meetup  July 28thGetting to The Loop - London Wordpress Meetup  July 28th
Getting to The Loop - London Wordpress Meetup July 28th
 
Zend framework
Zend frameworkZend framework
Zend framework
 
Developing apps using Perl
Developing apps using PerlDeveloping apps using Perl
Developing apps using Perl
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
 
Keeping it small - Getting to know the Slim PHP micro framework
Keeping it small - Getting to know the Slim PHP micro frameworkKeeping it small - Getting to know the Slim PHP micro framework
Keeping it small - Getting to know the Slim PHP micro framework
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
 
Mojolicious - A new hope
Mojolicious - A new hopeMojolicious - A new hope
Mojolicious - A new hope
 
What happens in laravel 4 bootstraping
What happens in laravel 4 bootstrapingWhat happens in laravel 4 bootstraping
What happens in laravel 4 bootstraping
 
Introduction to AJAX In WordPress
Introduction to AJAX In WordPressIntroduction to AJAX In WordPress
Introduction to AJAX In WordPress
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
 
Keeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkKeeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro Framework
 
Dance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech TalkDance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech Talk
 
Codeigniter : Using Third Party Components - Zend Framework Components
Codeigniter : Using Third Party Components - Zend Framework ComponentsCodeigniter : Using Third Party Components - Zend Framework Components
Codeigniter : Using Third Party Components - Zend Framework Components
 
An introduction to Laravel Passport
An introduction to Laravel PassportAn introduction to Laravel Passport
An introduction to Laravel Passport
 
How to migrate Cakephp 1.x to 2.x
How to migrate Cakephp 1.x to 2.xHow to migrate Cakephp 1.x to 2.x
How to migrate Cakephp 1.x to 2.x
 

Viewers also liked

Beyond The Browser - Creating a RESTful Web Service With WordPress
Beyond The Browser - Creating a RESTful Web Service With WordPressBeyond The Browser - Creating a RESTful Web Service With WordPress
Beyond The Browser - Creating a RESTful Web Service With WordPress
Christopher Reding
 
Introduction to plugin development
Introduction to plugin developmentIntroduction to plugin development
Introduction to plugin development
Caldera Labs
 
The Design Dilemma – WCATL
The Design Dilemma – WCATLThe Design Dilemma – WCATL
The Design Dilemma – WCATL
Mallie Hart
 
Webinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST APIWebinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST API
WP Engine UK
 
Five events in the life of every WordPress request you should know
Five events in the life of every WordPress request you should knowFive events in the life of every WordPress request you should know
Five events in the life of every WordPress request you should know
Caldera Labs
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
Jeroen van Dijk
 
Locking Down Your WordPress Site
Locking Down Your WordPress SiteLocking Down Your WordPress Site
Locking Down Your WordPress Site
Frank Corso
 
Less js-&-wp
Less js-&-wpLess js-&-wp
Less js-&-wp
rfair404
 
WordCamp Milwaukee 2012 - Aaron Saray - Secure Wordpress Coding
WordCamp Milwaukee 2012 - Aaron Saray - Secure Wordpress CodingWordCamp Milwaukee 2012 - Aaron Saray - Secure Wordpress Coding
WordCamp Milwaukee 2012 - Aaron Saray - Secure Wordpress Coding
Aaron Saray
 
Como oferecer boas experiências online com a criação de sites de qualidade - ...
Como oferecer boas experiências online com a criação de sites de qualidade - ...Como oferecer boas experiências online com a criação de sites de qualidade - ...
Como oferecer boas experiências online com a criação de sites de qualidade - ...
Keyla Silva
 
Reduzindo Tempo de Resposta do Servidor - WordCamp BH 2014
Reduzindo Tempo de Resposta do Servidor - WordCamp BH 2014Reduzindo Tempo de Resposta do Servidor - WordCamp BH 2014
Reduzindo Tempo de Resposta do Servidor - WordCamp BH 2014Celso Fernandes
 
WordPress for Beginners
WordPress for BeginnersWordPress for Beginners
WordPress for Beginners
Brad Williams
 
Future of wordpress in Nashville
Future of wordpress in NashvilleFuture of wordpress in Nashville
Future of wordpress in Nashville
Ah So Designs
 
Categories, Tags, Custom Post Types! Oh My!
Categories, Tags, Custom Post Types! Oh My!Categories, Tags, Custom Post Types! Oh My!
Categories, Tags, Custom Post Types! Oh My!sprclldr
 
Truly Dynamic Sidebars for WordPress
Truly Dynamic Sidebars for WordPressTruly Dynamic Sidebars for WordPress
Truly Dynamic Sidebars for WordPressednailor
 
CSI: WordPress -- Getting Into the Guts
CSI: WordPress -- Getting Into the GutsCSI: WordPress -- Getting Into the Guts
CSI: WordPress -- Getting Into the Guts
Dougal Campbell
 
Website Security - It Begins With Good Posture
Website Security - It Begins With Good PostureWebsite Security - It Begins With Good Posture
Website Security - It Begins With Good PostureTony Perez
 
10 Tips to Make WordPress Your Friend
10 Tips to Make WordPress Your Friend 10 Tips to Make WordPress Your Friend
10 Tips to Make WordPress Your Friend
Kerch McConlogue
 
Make Cash. Using Open Source. And WordPress.
Make Cash. Using Open Source. And WordPress.Make Cash. Using Open Source. And WordPress.
Make Cash. Using Open Source. And WordPress.
sogrady
 

Viewers also liked (20)

Beyond The Browser - Creating a RESTful Web Service With WordPress
Beyond The Browser - Creating a RESTful Web Service With WordPressBeyond The Browser - Creating a RESTful Web Service With WordPress
Beyond The Browser - Creating a RESTful Web Service With WordPress
 
Robert Riggs LOR
Robert Riggs LORRobert Riggs LOR
Robert Riggs LOR
 
Introduction to plugin development
Introduction to plugin developmentIntroduction to plugin development
Introduction to plugin development
 
The Design Dilemma – WCATL
The Design Dilemma – WCATLThe Design Dilemma – WCATL
The Design Dilemma – WCATL
 
Webinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST APIWebinar: AngularJS and the WordPress REST API
Webinar: AngularJS and the WordPress REST API
 
Five events in the life of every WordPress request you should know
Five events in the life of every WordPress request you should knowFive events in the life of every WordPress request you should know
Five events in the life of every WordPress request you should know
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
 
Locking Down Your WordPress Site
Locking Down Your WordPress SiteLocking Down Your WordPress Site
Locking Down Your WordPress Site
 
Less js-&-wp
Less js-&-wpLess js-&-wp
Less js-&-wp
 
WordCamp Milwaukee 2012 - Aaron Saray - Secure Wordpress Coding
WordCamp Milwaukee 2012 - Aaron Saray - Secure Wordpress CodingWordCamp Milwaukee 2012 - Aaron Saray - Secure Wordpress Coding
WordCamp Milwaukee 2012 - Aaron Saray - Secure Wordpress Coding
 
Como oferecer boas experiências online com a criação de sites de qualidade - ...
Como oferecer boas experiências online com a criação de sites de qualidade - ...Como oferecer boas experiências online com a criação de sites de qualidade - ...
Como oferecer boas experiências online com a criação de sites de qualidade - ...
 
Reduzindo Tempo de Resposta do Servidor - WordCamp BH 2014
Reduzindo Tempo de Resposta do Servidor - WordCamp BH 2014Reduzindo Tempo de Resposta do Servidor - WordCamp BH 2014
Reduzindo Tempo de Resposta do Servidor - WordCamp BH 2014
 
WordPress for Beginners
WordPress for BeginnersWordPress for Beginners
WordPress for Beginners
 
Future of wordpress in Nashville
Future of wordpress in NashvilleFuture of wordpress in Nashville
Future of wordpress in Nashville
 
Categories, Tags, Custom Post Types! Oh My!
Categories, Tags, Custom Post Types! Oh My!Categories, Tags, Custom Post Types! Oh My!
Categories, Tags, Custom Post Types! Oh My!
 
Truly Dynamic Sidebars for WordPress
Truly Dynamic Sidebars for WordPressTruly Dynamic Sidebars for WordPress
Truly Dynamic Sidebars for WordPress
 
CSI: WordPress -- Getting Into the Guts
CSI: WordPress -- Getting Into the GutsCSI: WordPress -- Getting Into the Guts
CSI: WordPress -- Getting Into the Guts
 
Website Security - It Begins With Good Posture
Website Security - It Begins With Good PostureWebsite Security - It Begins With Good Posture
Website Security - It Begins With Good Posture
 
10 Tips to Make WordPress Your Friend
10 Tips to Make WordPress Your Friend 10 Tips to Make WordPress Your Friend
10 Tips to Make WordPress Your Friend
 
Make Cash. Using Open Source. And WordPress.
Make Cash. Using Open Source. And WordPress.Make Cash. Using Open Source. And WordPress.
Make Cash. Using Open Source. And WordPress.
 

Similar to Extending the WordPress REST API - Josh Pollock

Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?
Yevhen Kotelnytskyi
 
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Mike Schinkel
 
WordPress Plugin development
WordPress Plugin developmentWordPress Plugin development
WordPress Plugin development
Mostafa Soufi
 
Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0
Yevhen Kotelnytskyi
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
Hisateru Tanaka
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryRemedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryTatsuhiko Miyagawa
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overviewjsmith92
 
Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stack
Paul Bearne
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)arcware
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
Bo-Yi Wu
 
Drupal vs WordPress
Drupal vs WordPressDrupal vs WordPress
Drupal vs WordPress
Walter Ebert
 
Best Practices for creating WP REST API by Galkin Nikita
Best Practices for creating WP REST API by Galkin NikitaBest Practices for creating WP REST API by Galkin Nikita
Best Practices for creating WP REST API by Galkin Nikita
WordCamp Kyiv
 
Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
Pavel Makhrinsky
 
Laravel5 Introduction and essentials
Laravel5 Introduction and essentialsLaravel5 Introduction and essentials
Laravel5 Introduction and essentials
Pramod Kadam
 
WordPress Café: Using WordPress as a Framework
WordPress Café: Using WordPress as a FrameworkWordPress Café: Using WordPress as a Framework
WordPress Café: Using WordPress as a Framework
Exove
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
Kris Wallsmith
 
Express.pdf
Express.pdfExpress.pdf
Express.pdf
stephanedjeukam1
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5
Darren Craig
 
Resource Routing in ExpressionEngine
Resource Routing in ExpressionEngineResource Routing in ExpressionEngine
Resource Routing in ExpressionEngine
MichaelRog
 
WordPress plugin #3
WordPress plugin #3WordPress plugin #3
WordPress plugin #3
giwoolee
 

Similar to Extending the WordPress REST API - Josh Pollock (20)

Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?Как получить чёрный пояс по WordPress?
Как получить чёрный пояс по WordPress?
 
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
 
WordPress Plugin development
WordPress Plugin developmentWordPress Plugin development
WordPress Plugin development
 
Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0Как получить чёрный пояс по WordPress? v2.0
Как получить чёрный пояс по WordPress? v2.0
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQueryRemedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 
Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stack
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
Drupal vs WordPress
Drupal vs WordPressDrupal vs WordPress
Drupal vs WordPress
 
Best Practices for creating WP REST API by Galkin Nikita
Best Practices for creating WP REST API by Galkin NikitaBest Practices for creating WP REST API by Galkin Nikita
Best Practices for creating WP REST API by Galkin Nikita
 
Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
 
Laravel5 Introduction and essentials
Laravel5 Introduction and essentialsLaravel5 Introduction and essentials
Laravel5 Introduction and essentials
 
WordPress Café: Using WordPress as a Framework
WordPress Café: Using WordPress as a FrameworkWordPress Café: Using WordPress as a Framework
WordPress Café: Using WordPress as a Framework
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
Express.pdf
Express.pdfExpress.pdf
Express.pdf
 
What's New In Laravel 5
What's New In Laravel 5What's New In Laravel 5
What's New In Laravel 5
 
Resource Routing in ExpressionEngine
Resource Routing in ExpressionEngineResource Routing in ExpressionEngine
Resource Routing in ExpressionEngine
 
WordPress plugin #3
WordPress plugin #3WordPress plugin #3
WordPress plugin #3
 

More from Caldera Labs

Slightly Advanced Topics in Gutenberg Development
Slightly Advanced Topics in Gutenberg Development Slightly Advanced Topics in Gutenberg Development
Slightly Advanced Topics in Gutenberg Development
Caldera Labs
 
Financial Forecasting For WordPress Businesses
Financial Forecasting For WordPress BusinessesFinancial Forecasting For WordPress Businesses
Financial Forecasting For WordPress Businesses
Caldera Labs
 
Five Attitudes Stopping You From Building Accessible Wordpress Websites
Five Attitudes Stopping You From Building Accessible Wordpress WebsitesFive Attitudes Stopping You From Building Accessible Wordpress Websites
Five Attitudes Stopping You From Building Accessible Wordpress Websites
Caldera Labs
 
Our Hybrid Future: WordPress As Part of the Stack #WCNYC
Our Hybrid Future: WordPress As Part of the Stack #WCNYCOur Hybrid Future: WordPress As Part of the Stack #WCNYC
Our Hybrid Future: WordPress As Part of the Stack #WCNYC
Caldera Labs
 
Our Hybrid Future: WordPress As Part of the Stack
Our Hybrid Future: WordPress As Part of the StackOur Hybrid Future: WordPress As Part of the Stack
Our Hybrid Future: WordPress As Part of the Stack
Caldera Labs
 
Introduction to VueJS & The WordPress REST API
Introduction to VueJS & The WordPress REST APIIntroduction to VueJS & The WordPress REST API
Introduction to VueJS & The WordPress REST API
Caldera Labs
 
It all starts with a story
It all starts with a storyIt all starts with a story
It all starts with a story
Caldera Labs
 
A/B Testing FTW
A/B Testing FTWA/B Testing FTW
A/B Testing FTW
Caldera Labs
 
WPSessions Composer for WordPress Plugin Development
WPSessions Composer for WordPress Plugin DevelopmentWPSessions Composer for WordPress Plugin Development
WPSessions Composer for WordPress Plugin DevelopmentCaldera Labs
 
Josh Pollock #wcatl using composer to increase your word press development po...
Josh Pollock #wcatl using composer to increase your word press development po...Josh Pollock #wcatl using composer to increase your word press development po...
Josh Pollock #wcatl using composer to increase your word press development po...
Caldera Labs
 
Content Marketing With WordPress -- Tallahassee WordPress Meetup
Content Marketing With WordPress -- Tallahassee WordPress MeetupContent Marketing With WordPress -- Tallahassee WordPress Meetup
Content Marketing With WordPress -- Tallahassee WordPress Meetup
Caldera Labs
 
Writing About WordPress: Helping Yourself, by Helping Others -- WordCamp Orl...
Writing About WordPress: Helping Yourself, by Helping Others -- WordCamp Orl...Writing About WordPress: Helping Yourself, by Helping Others -- WordCamp Orl...
Writing About WordPress: Helping Yourself, by Helping Others -- WordCamp Orl...
Caldera Labs
 
WordPress Tallahassee Meetup: Turning WordPress Sites Into Web & Mobile Apps
WordPress Tallahassee Meetup: Turning WordPress Sites Into Web & Mobile AppsWordPress Tallahassee Meetup: Turning WordPress Sites Into Web & Mobile Apps
WordPress Tallahassee Meetup: Turning WordPress Sites Into Web & Mobile Apps
Caldera Labs
 

More from Caldera Labs (13)

Slightly Advanced Topics in Gutenberg Development
Slightly Advanced Topics in Gutenberg Development Slightly Advanced Topics in Gutenberg Development
Slightly Advanced Topics in Gutenberg Development
 
Financial Forecasting For WordPress Businesses
Financial Forecasting For WordPress BusinessesFinancial Forecasting For WordPress Businesses
Financial Forecasting For WordPress Businesses
 
Five Attitudes Stopping You From Building Accessible Wordpress Websites
Five Attitudes Stopping You From Building Accessible Wordpress WebsitesFive Attitudes Stopping You From Building Accessible Wordpress Websites
Five Attitudes Stopping You From Building Accessible Wordpress Websites
 
Our Hybrid Future: WordPress As Part of the Stack #WCNYC
Our Hybrid Future: WordPress As Part of the Stack #WCNYCOur Hybrid Future: WordPress As Part of the Stack #WCNYC
Our Hybrid Future: WordPress As Part of the Stack #WCNYC
 
Our Hybrid Future: WordPress As Part of the Stack
Our Hybrid Future: WordPress As Part of the StackOur Hybrid Future: WordPress As Part of the Stack
Our Hybrid Future: WordPress As Part of the Stack
 
Introduction to VueJS & The WordPress REST API
Introduction to VueJS & The WordPress REST APIIntroduction to VueJS & The WordPress REST API
Introduction to VueJS & The WordPress REST API
 
It all starts with a story
It all starts with a storyIt all starts with a story
It all starts with a story
 
A/B Testing FTW
A/B Testing FTWA/B Testing FTW
A/B Testing FTW
 
WPSessions Composer for WordPress Plugin Development
WPSessions Composer for WordPress Plugin DevelopmentWPSessions Composer for WordPress Plugin Development
WPSessions Composer for WordPress Plugin Development
 
Josh Pollock #wcatl using composer to increase your word press development po...
Josh Pollock #wcatl using composer to increase your word press development po...Josh Pollock #wcatl using composer to increase your word press development po...
Josh Pollock #wcatl using composer to increase your word press development po...
 
Content Marketing With WordPress -- Tallahassee WordPress Meetup
Content Marketing With WordPress -- Tallahassee WordPress MeetupContent Marketing With WordPress -- Tallahassee WordPress Meetup
Content Marketing With WordPress -- Tallahassee WordPress Meetup
 
Writing About WordPress: Helping Yourself, by Helping Others -- WordCamp Orl...
Writing About WordPress: Helping Yourself, by Helping Others -- WordCamp Orl...Writing About WordPress: Helping Yourself, by Helping Others -- WordCamp Orl...
Writing About WordPress: Helping Yourself, by Helping Others -- WordCamp Orl...
 
WordPress Tallahassee Meetup: Turning WordPress Sites Into Web & Mobile Apps
WordPress Tallahassee Meetup: Turning WordPress Sites Into Web & Mobile AppsWordPress Tallahassee Meetup: Turning WordPress Sites Into Web & Mobile Apps
WordPress Tallahassee Meetup: Turning WordPress Sites Into Web & Mobile Apps
 

Recently uploaded

Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Sanjeev Rampal
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
laozhuseo02
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
nirahealhty
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
Arif0071
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
Gal Baras
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
Rogerio Filho
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
3ipehhoa
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
JeyaPerumal1
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
3ipehhoa
 
BASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptxBASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptx
natyesu
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
3ipehhoa
 
Output determination SAP S4 HANA SAP SD CC
Output determination SAP S4 HANA SAP SD CCOutput determination SAP S4 HANA SAP SD CC
Output determination SAP S4 HANA SAP SD CC
ShahulHameed54211
 
ER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAEER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAE
Himani415946
 
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptxLiving-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
TristanJasperRamos
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
laozhuseo02
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
JungkooksNonexistent
 

Recently uploaded (16)

Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
 
BASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptxBASIC C++ lecture NOTE C++ lecture 3.pptx
BASIC C++ lecture NOTE C++ lecture 3.pptx
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
 
Output determination SAP S4 HANA SAP SD CC
Output determination SAP S4 HANA SAP SD CCOutput determination SAP S4 HANA SAP SD CC
Output determination SAP S4 HANA SAP SD CC
 
ER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAEER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAE
 
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptxLiving-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
Living-in-IT-era-Module-7-Imaging-and-Design-for-Social-Impact.pptx
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
 

Extending the WordPress REST API - Josh Pollock

  • 2. Hi, I'm Josh Slides: JoshPress.net/extending-rest-api-talk
  • 3. What We Are Covering Extending The Default Responses v2.wp-api. org/extending/modifyi Creating Your Own Endpoints v2.wp-api. org/extending/adding/
  • 4. We're Skipping To The Back of The Book:) Download: wpeng.in/wp-api-ebook/
  • 5. Let's Talk About Defaults
  • 6. Why Extend The Defaults? Are endpoints of a default endpoint close, but missing a field? Combine POST requests. add_filter( 'the_content', function( $content ) { … add_filter( 'template_includes', function( $template ) { ...
  • 7. Why Make Your Own? ● Unique data sets -- custom queries, custom tables, wrapping existing classes. ● Just the data you need. ● Replace admin-ajax $query = new WP_Query( $args ); $collection = new my_class( $params ); global $wpdb; add_rewrite_rule('^leaf/([0-9]+)/?', 'index.php?page_id=$matches[1]', 'top');
  • 8. Anatomy Of A REST Request WP_REST_SERVER ??WP_REST_Request WP_REST_Response
  • 10. Customizing Default Routes ● Add fields to response ○ Custom field or any other data ● Applies to all read and/or write endpoints of route.
  • 11. Meet register_api_field() http://v2.wp-api.org/extending/modifying/ ● Adds fields to one or more response ● Arguments: ○ Object (post type name or "terms", "meta", "user" or "comments" ) ○ Name of field ○ Args ■ Read Callback ■ Write Callback ■ Schema Callback
  • 12. Example Handlers function slug_get_meta_field( $object, $field_name, $request ) { return get_post_meta( $object[ 'id' ], $field_name ); } public function slug_update_meta( $value, $object, $field_name ) { if ( ! $value || ! is_string( $value ) ) { return; } return update_post_meta( $object->ID, $field_name, strip_tags( $value ) ); }
  • 13. Example Registration add_action( 'rest_api_init', 'slug_register_spaceship' ); function slug_register_spaceship() { register_api_field( 'post', 'starship', array( 'get_callback' => slug_get_meta_field, 'update_callback' => slug_update_meta_field, 'schema' => null, ) ); }
  • 14. Adding Your Own Endpoints
  • 15. Anatomy Of A REST Request WP_REST_SERVER Your RouteWP_REST_Request WP_REST_Response
  • 16. Request -> Callback -> Response Check Permission Validate Fields Sanitize Fields Callback Response
  • 17. Meet register_rest_route() http://v2.wp-api.org/extending/adding/ Adds a collection of routes. add_action( 'rest_api_init', function () { register_rest_route( 'myplugin/v1', '/author/(? P<id>d+)', array( 'methods' => 'GET', 'callback' => 'my_awesome_func', ) ); } );
  • 19. register_rest_route() Defines ● Endpoints For Route ● Permissions for endpoints ● Transport methods for endpoints ● Fields for endpoints ● Callback for endpoints ● Schema
  • 20. Endpoint URL public function the_route() { register_rest_route( 'swp_api', '/search', array( ) ); } Namespace Route
  • 21. Transport Method public function the_route() { register_rest_route( 'swp_api', '/search', array( 'methods' => WP_REST_Server::READABLE, ) ); } GET
  • 22. Permissions public function the_route() { register_rest_route( 'swp_api', '/search', array( 'methods' => WP_REST_Server::READABLE, 'permission_callback' => array( $this, 'permissions_check' ) ) ); }
  • 23. Permissions public function permissions_check( $request ) { $allowed = apply_filters( 'cwp_swp_api_allow_query', true, $request ); return (bool) $allowed; } public function permissions_check( $request ) { return current_user_can( 'something' ); } Standard WordPress Permissions/ Authentication!!!!!!!!!
  • 24. Fields public function the_route() { register_rest_route( 'swp_api', '/search', array( 'methods' => WP_REST_Server::READABLE, 'permission_callback' => array( $this, 'permissions_check' ), 'args' => $this->the_args(), ) ); }
  • 25. Fields $args = array( 's' => array( 'default' => '', 'sanitize_callback' => 'sanitize_text_field', ), 'engine' => array( 'default' => 'default', 'sanitize_callback' => 'sanitize_text_field', 'validate_callback' => array( $this, 'validate_engine' ), ), 'page' => array( 'default' => 1, 'sanitize_callback' => 'absint', ), );
  • 26. Callback public function the_route() { register_rest_route( 'swp_api', '/search', array( 'methods' => WP_REST_Server::READABLE, 'permission_callback' => array( $this, 'permissions_check' ), 'args' => $this->the_args(), 'callback' => array( $this, 'callback' ), ) ); }
  • 27. Callback public function callback( $request ) { $params = $request->get_params(); $cb_class = new class_that_does_something( $params ); $results = $cb_class->get_results(); if( is_array( $results ) { return rest_ensure_response( $results, 200 ); }elseif( is_wp_error( $results ) ) { return rest_ensure_response( $results, 500 ); }else{ return rest_ensure_response( __( 'FAIL!', 'text-domain' ), 500 ); } }
  • 28. Response Should be either: ● An instance of WP_REST_Response ● An instance of WP_Error rest_ensure_response( $data, $code, $headers );
  • 29. You're Ready To Learn More JoshPress.net/extending-rest-api-talk wpeng.in/wp-api-ebook/ That's About It