WordPress REST API

best practise & use cases

Photocredit: berlin.wordcamp.org

WordCamp Berlin 2015

Wer wir sind

Birgit Olzem

  • Coach & Consultant
  • WordPress Trainerin
  • mindcopter GmbH
  • Gerolstein / Vulkaneifel
  • @CoachBirgit

Hinnerk Altenburg

  • Plugin-Entwickler
  • Team-Sucher
  • WP-ImmoMakler®
  • Lüneburg /Hamburg
  • @hinnerk_a

Ziel des Talk

Was wollen wir erreichen?

WP-API

Was ist die WordPress REST API?

Das WP-API Projekt

Access your site's data through an easy-to-use HTTP REST API

wp-api.org

Akronyme kurz & bündig

  • WP = WordPress
  • API = Application Program Interface
  • REST = REpresentational State Transfer
  • JSON = JavaScript Object Notation

CRUD

  • Create =POST
  • Read = GET
  • Update = PUT
  • Delete = DELETE

Datenbank Operationen via HTTP (REST)

Folgende CRUD Operationen möglich


posts

post meta

post revision

pages

media

comments

taxonomies

terms

users

Hä?

Wo die WP REST API einsetzen?

Wie geht´s?

Endpunkte & Routen 

Sammle Daten aus WordPress (Core)

Version 1.x (legacy):
https://domain.tld/wp-json/

 

Version 2.x beta (bald im Core): 
https://domain.tld/wp-json/wp/v2

Modifiziere post_data

// Use this filter to filter output for posts.
// Change 'post' to whatever resource (user, media, comment, etc) to filter
add_filter( 'rest_prepare_post', 'remove_post_data', 10, 3 );

function remove_post_data( $data, $post, $request ) {
   unset( $data->data['sticky'] ); // Don't show this!

   return $data;
}

Daten zu post_data

// Add fields to posts
add_action( 'rest_api_init', 'post_register_random_info' );
function post_register_random_info() {
   register_api_field( 'post', // What api resource to target, post, page, user etc
      'random_info', // Name of field
      array(
         'get_callback'    => 'get_random_info', // Get callback
         'update_callback' => null, // Put callback
         'schema'          => null,
      )
   );
}

// Just return some random data
function get_random_info( $object, $field_name, $request ) {
   $data = array(
      'data' => md5( rand( 0, 100000 ) ),
   );

   return $data;
}

Daten zu author data

// Add extra fields to user
add_action( 'rest_api_init', 'slug_register_user_info' );
function slug_register_user_info() {
   register_api_field( 'user', // What api resource to target, post, page, user etc
      'user_extra_info', // Name of field
      array(
         'get_callback'    => 'get_user_extra_info', // Get callback
         'update_callback' => null, // Put callback
         'schema'          => null,
      )
   );
}

// Callback for getting extra user info
function get_user_extra_info( $object, $field_name, $request ) {
   $data = array(
      'twitter'   => get_the_author_meta( 'twitter', $object['id'] ),
      'facebook'  => get_the_author_meta( 'facebook', $object['id'] ),
      'instagram' => get_the_author_meta( 'instagram', $object['id'] ),
   );

   return $data;
}

Entferne Endpunkte

// Filter endpoints, removing those not wanted
add_filter( 'rest_endpoints', 'filter_endpoints', 20, 1 );

function filter_endpoints( $endpoints ) {
   // Patterns available at the root of the api
   $disable_endpoints = array(
      '/wp/v2/media',
      '/wp/v2/media/(?P<id>[\d]+)',
      '/wp/v2/comments',
      '/wp/v2/comments/(?P<id>[\d]+)',
   );

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

   return $endpoints;
}

neue Endpunkte

// Register new route/endpoint
add_action( 'rest_api_init', function () {
   register_rest_route(
      'cb/v2', // Namespace for route/endpoint
      '/myroute', // Route to be used, can contain regexp
      array(
         'methods'  => 'GET', // Endpoint, get
         'callback' => 'cb_get_myroute', // Call this function
         'args'     => array(), // Optional args, validation etc
      )
   );
} );

Teil 1:

​rest_api_init

neue Endpunkte

function cb_get_myroute( $args = null ) {
   $posts = get_posts(
      array(
         'posts_per_page' => 1,
         'post_status'    => 'publish',
         'orderby'        => 'rand',
      )
   );
   $data  = array(
      'info'        => date( 'Ymdhis', time() ) . '/' . time(),
      'random_post' => $posts,
   );

   if ( empty( $posts ) ) {
      return new WP_Error( 'cb_no_posts', 'No posts available!', array( 'status' => 404 ) );
   }

   return new WP_REST_Response( $data, 200 );
}

Teil 2:

​Setze Argumente in Funktion

Einfach, oder?

Sicherheit

Authentifizierung

http://v2.wp-api.org/guide/authentication/

  • Cookies (WP themes and plugins)
  • Basic Auth (dev/staging)
  • OAuth1 (production)

Anwendungsbeispiele

WP Live Search

Photocredit: wptavern.com

https://wordpress.org/plugins/wp-search-live/

Reactor / AppPresser

ACF to WP-API

WP-API angular.js

http://shprink.github.io/wp-api-angularjs/

WordPress Hybrid Client

http://wphc.julienrenaux.fr/

Und was noch?

Plugin-Vielfalt

viele Plugins haben eigene

 REST API Endpunkte

Advanced Custom Fields

PODs REST API

BuddyPress REST API

WooCommerce REST API

Themes

Picard (react + WP API)

Custom Post Types
und REST API

CPT "Books" => API

function cb_add_book_args() {
    global $wp_post_types;
 
    $wp_post_types['book']->show_in_rest = true;
    $wp_post_types['book']->rest_base = 'book';
    $wp_post_types['book']->rest_controller_class = 'WP_REST_Posts_Controller';
}
add_action( 'init', 'cb_add_book_args', 30 );

register_post_type_args

function cb_add_cpts_to_api( $args, $post_type ) {
    if ( 'movie' === $post_type ) {
        $args['show_in_rest'] = true;
        $args['rest_base'] = 'movie';
        // $args['rest_controller_class'] = 'WP_REST_Posts_Controller';
    }
    return $args;
}
add_filter( 'register_post_type_args', 'cb_add_cpts_to_api', 10, 2 );

Aufruf

domain.tld/wp-json/wp/v2/book

Hybrid Apps mit WP REST API & IONIC Framework

Ressourcen

  • http://wphc.julienrenaux.fr/
  • https://github.com/scottopolis/wpIonic
  • https://apppresser.com/
  • http://codecanyon.net/item/ionwp-ionic-phonegapcordova-wordpress-app/13444998
  • http://codecanyon.net/item/ionwordpress-wordpress-full-integrated-mobile-app/10639789

Noch Fragen?

DANKESCHÖN

sagt CoachBirgit

WordPress REST API - best practise & use cases

By CoachBirgit

WordPress REST API - best practise & use cases

Introduction into the WordPress REST API. This are the Slides from my talk on WordCamp Berlin 2015 held in german.

  • 5,549