Įvadas į
WordPress
REST API

Arūnas Liuiza

WordPress Core Contributor, WordPress Kaunas Meetup co-organizer, WordCamp (Lithuania, Riga, Stockholm, Jyväskylä) speaker and one of the editors of the Lithuanian WordPress translation team.

 

Free & premium WordPress plugin developer:

WordPress Expert on Codeable;

Founder of Arunas.co / EcoSim / TryoutWP;

Lecturer at Kaunas College.

WP REST API

Kas tas REST API?

  • Būdas skirtingoms kompiuterinėms sistemoms bendrauti Internetu
     
  • CRUD per HTTP metodus:
    • Create - PUT/POST
    • Read - GET
    • Update - POST/PUT/PATCH
    • Delete - DELETE

REST in WordPress

  • Padaro WordPress turinį prieinamą per API
  • JSON API įskiepis - nuo 2009 metų;
  • WP REST API feature įskiepis - nuo 2013 metų;
  • Core pilnai - nuo 4.7 versijos (2017 sausis);
     
  • example.com/wp-json/wp/v2
    example.com/wp-json/wp/v2/posts
    
    example.com/wp-json/wp/v2/posts/15

Prieinami resursai

  • Posts
  • Pages
  • Media
  • Custom Post Types
  • Post Meta
  • Revisions
  • Comments
  • Terms
  • Users

Kam to reikia?

  • AJAX
  • JavaScript aplikacijos
  • Mobiliosios aplikacijos
  • Duomenų importavimas/eksportavimas
  • Nestandartiniai valdymo skydeliai
  • ir t.t.

Trūkumai

Išplėtimas

Atsakymų modifikavimas

add_action( 'rest_api_init', function () {
    register_rest_field( 'comment', 'karma', array(
        'get_callback' => function( $comment_arr ) {
            $comment_obj = get_comment( $comment_arr['id'] );
            return (int) $comment_obj->comment_karma;
        },
        'update_callback' => function( $karma, $comment_obj ) {
            $ret = wp_update_comment( array(
                'comment_ID'    => $comment_obj->comment_ID,
                'comment_karma' => $karma
            ) );
            if ( false === $ret ) {
                return new WP_Error(
                  'rest_comment_karma_failed',
                  __( 'Failed to update comment karma.' ),
                  array( 'status' => 500 )
                );
            }
            return true;
        },
        'schema' => array(
            'description' => __( 'Comment karma.' ),
            'type'        => 'integer'
        ),
    ) );
} );

Nauji endpoint'ai

add_action( 'rest_api_init', function () {
  register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array(
    'methods' => 'GET',
    'callback' => 'my_awesome_func',
    'args' => array(
      'id' => array(
        'validate_callback' => function($param, $request, $key) {
          return is_numeric( $param );
        }
      ),
    ),
    'permission_callback' => function () {
      return current_user_can( 'edit_others_posts' );
    }
  ) );
} );
function my_awesome_func( $data ) {
  $posts = get_posts( array(
    'author' => $data['id'],
  ) );
 
  if ( empty( $posts ) ) {
    return new WP_Error( 'no_author', 'Invalid author', array( 'status' => 404 ) );
  }
 
  return $posts[0]->post_title;
}

Klausimai