Building great things with the

WP-API

2015-05-19, WordPress Meetup #2

Agenda

  • The WP rest API
  • Short background
  • Why WP-API
  • How to get started
  • What we built with it
  • Some tips and tricks
  • Other examples
  • What’s next?
  • Other resources

Who am I?

Christoffer Larsson - @chredd

WordPress Rest API

API?

API: Application Program Interface

http://en.wikipedia.org/wiki/Application_programming_interface

REST?

REST: Representational State Transfer

http://en.wikipedia.org/wiki/Representational_state_transfer

JSON?

JSON: JavaScript Object Notation

http://json.org/

The WP-API project

http://wptavern.com/ryan-mccue-on-creating-the-json-rest-api-for-wordpress

But why?

I'll tell you why!

How do I get started?

  • https://wordpress.org/plugins/json-rest-api/
  • https://github.com/WP-API/WP-API
  • http://wp-api.org/
  • http://v2.wp-api.org/

What we built

And things we learned

Fetching data

Post data

Discovery block

List categories (Wired.com)

Modify post data


add_filter( 'json_prepare_post', 'add_post_data', 10, 3 );

function add_post_data( $_post, $post, $context ) {
	$_post['post_title'] = 'Hello World';
	[...]
	return $_post;	
}
					

Modify author data


add_filter( 'json_prepare_user', 'add_user_metadata', 10, 3 );

function add_user_metadata( $user_fields, $user, $context ) {
	add_author_meta_field( $user_fields, 'twitter' );
	[...]
	return $user_fields;
}

function add_author_meta_field( &$user_fields, $field ) {
	if ( $meta = get_the_author_meta( $field, $user_fields['ID'] ) ) {
		$user_fields[ $field ] = $meta;
	}
}
					

Removing endpoints


add_filter( 'json_endpoints', 'filter_endpoints', 20, 1 );

function filter_endpoints( $endpoints ) {
	$disable_endpoints = array(
		'/taxonomies',
		'/media',
		'/pages',
		[...]
	);

	foreach ( $disable_endpoints as $disable ) {
		if ( isset( $endpoints[ $disable ] ) ) {
			unset( $endpoints[ $disable ] );
		}
	}

	return $endpoints;
}
					

Adding endpoints


add_filter( 'json_endpoints', 'filter_endpoints', 20, 1 );

function filter_endpoints( $endpoints ) {
	
	$endpoints['/discovery'] = array(
		array( 'get_discovery', \WP_JSON_Server::READABLE ),
	);
	[...]

	return $endpoints;
}
					

Authentication

Some other examples

What's next?

More reading / resources

Questions?

@chredd

[email protected]