Utilizing the WP REST API

Utilizing the WP REST API

Throughout this presentation Rachel will teach us how to leverage the WP REST API for a multitude of different projects. We’ll start with installing and activation the API itself (and important place to begin), and cover some of the caveats that go along with running an API from a publicly-accessible server. From here we’ll look at what kinds of data are available to you and how you can access them, both from your own site and from any other site with the API enabled.

Once we know how to interact with the core API methods we’re going to dive in to manipulating and extending the data that they return. Maybe you need a bit more information about a post… maybe you want to provide a bit less. Good news, there are hooks for that! After that we’ll look at creating our own custom endpoints. The REST API has been specifically written (and re-written) with extensibility in mind.

By the end of this presentation you’ll have enough working knowledge of the WP REST API that you’ll be able to immediately begin using it across any of your WordPress projects.

More information:
http://wpsessions.com/sessions/utilizing-the-wp-rest-api/

634b37a53babc18a5bda19722d5b41a3?s=128

Rachel Baker

May 26, 2015
Tweet

Transcript

  1. Rachel Baker Lead Developer : WP REST API Project Lead

    Engineer: The Wirecutter Utilizing the
  2. Getting Started

  3. Install the Plugin $ git clone https://github.com/WP-API/WP-API.git wp-rest-api Or download

    the latest v2.0 Beta release Clone the develop branch from Github into your plugins directory https://github.com/WP-API/WP-API/releases
  4. Available Endpoints

  5. Embed Related Data

  6. Embed the _links https://example.com/wp-json/wp/v2/posts/1?_embed "_links": { … "author": [ {

    "embeddable": true, "href": "http://local.wpapi.dev/wp-json/wp/v2/users/2" } ], … Hypermedia Application Language HAL
  7. Display Responses

  8. Posts Collection

  9. Using jQuery ( function( $, _ ) { var apiUrl

    = $( 'link[rel="https://github.com/WP-API/WP-API"]' ).attr( 'href' ), $el = $( '#js-data' ), tmpl = '<article id="post-<%= id %>"><h1><%= title %></h1><%= content %></article>'; $.get( apiUrl + '/wp/v2/posts', function( data ) { for ( var key in data ) { var output = { id : data[ key ].id, title : data[ key ].title.rendered, content : data[ key ].content.rendered }, $template = $( _.template( tmpl, output ) ); $el.append( $template ); } }); })( jQuery, _ ); and Underscore
  10. Using PHP $fetch = wp_remote_get( home_url( '/wp-json/wp/v2/posts' ), array() );

    // Add error checking. $response_data = wp_remote_retrieve_body( $fetch ); // Add error checking. $items = json_decode( $response_data ); $output = ''; foreach ( $items as $data ) { $output .= sprintf( '<article id="%d"><h2>%s</h2>%s</article>', $data->id, $data->title->rendered, $data->content->rendered ); } echo $output;
  11. Custom Post Types

  12. Include a Post Type

  13. Add Events Endpoints Using the init action function wpsd_add_tribe_events_args() {

    global $wp_post_types; $wp_post_types['tribe_events']->show_in_rest = true; $wp_post_types['tribe_events']->rest_base = 'tribe_events'; $wp_post_types['tribe_events']->rest_controller_class = 'WP_REST_Posts_Controller'; } add_action( 'init', 'wpsd_add_tribe_events_args', 30 );
  14. Add Events Endpoints function wpsd_add_tribe_events_args( $args ) { $args['show_in_rest'] =

    true; $args['rest_base'] = 'tribe_events'; $args['rest_controller_class'] = 'WP_REST_Posts_Controller'; return $args; } add_filter( 'tribe_events_register_event_type_args', 'wpsd_add_tribe_events_args' ); Using the tribe_events_register_event_type_args filter
  15. Modifying Endpoints

  16. Add an Endpoint Field

  17. Add Event URL Field function wpsd_register_event_url() { $schema = array(

    'type' => 'uri', 'description' => 'URL of the event', 'context' => array( 'view', 'edit' ), ); register_api_field( 'tribe_events', 'event_url', array( 'schema' => $schema, 'get_callback' => 'wpsd_event_url_get_callback', 'update_callback' => 'wpsd_event_url_update_callback', ) ); } add_action( 'rest_api_init', 'wpsd_register_event_url' );
  18. Event URL Field Callbacks function wpsd_event_url_get_callback( $post_data ) { $event_url

    = get_post_meta( $post_data['id'], '_EventURL', true ); return esc_url( $event_url ); } function wpsd_event_url_update_callback( $value, $post ) { if ( ! is_string( $value ) ) { return new WP_Error( 'rest_meta_event_url_invalid', __( 'The event_url value is expected to be a string.' ), array( 'status' => 403 ) ); } $value = esc_url_raw( $value ); $update = update_post_meta( $post->ID, '_EventURL', $value ); // Add error checking. return $update; }
  19. Filter Response Data

  20. Remove Ping Status function wpsd_remove_ping_status( $response ) { if (

    ! current_user_can( 'edit_posts' ) ) { unset( $response->data['ping_status'] ); } return $response; } add_filter( 'rest_prepare_post', 'wpsd_remove_ping_status' );
  21. Custom Endpoints

  22. Register a Route

  23. Register Options Routes function wpsd_add_options_routes() { $collection_args = array( 'methods'

    => WP_REST_Server::READABLE, 'callback' => 'wpsd_get_options', 'permission_callback' => 'wpsd_options_permission_check', ); $single_args = array( 'methods' => WP_REST_Server::READABLE, 'callback' => 'wpsd_get_option', 'permission_callback' => 'wpsd_options_permission_check', ); register_rest_route( 'wps_demo/v1', '/options', $collection_args ); register_rest_route( 'wps_demo/v1', '/options/(?P<key>[\w-]+)', $single_args ); } add_action( 'rest_api_init', 'wpsd_add_options_routes' ); Just an example of how to create your own route. Do NOT re-use this code.
  24. Check Route Permissions function wpsd_options_permission_check( $request ) { if (

    current_user_can( 'manage_options' ) ) { return true; } return new WP_Error( 'wpsd_options_access_denied', __( 'Shame on you! You should not be here.' ), array( 'status' => 403 ) ); }
  25. Handle Collection Request function wpsd_get_options( $request ) { $all_options =

    wp_load_alloptions(); $response = rest_ensure_response( $all_options ); $response->add_link( 'self', rest_url( '/wps_demo/v1/options' ) ); return $response; } Loading all the options like this is BAD! This is only an example.
  26. Handle Item Request function wpsd_get_option( $request ) { $key =

    sanitize_key( $request['key'] ); $option = array(); $option[ $key ] = get_option( $key ); // Add error handling. $response = rest_ensure_response( $option ); $response->add_link( 'self', rest_url( '/wps_demo/v1/options/' . $key ) ); $response->add_link( 'collection', rest_url( '/wps_demo/v1/options/' ) ); return $response; }
  27. Wrapping Up

  28. Version 2.0 Beta 2 Release Date: May 28, 2015 https://github.com/WP-API/WP-API

  29. https://speakerdeck.com/rachelbaker/utilizing-the-wp-rest-api Thank You! Slides: