Upgrade to Pro — share decks privately, control downloads, hide ads and more …

WP-API攻略

 WP-API攻略

PHPカンファレンス2017での資料です。

Takayuki Miyauchi

October 08, 2017
Tweet

More Decks by Takayuki Miyauchi

Other Decks in Technology

Transcript

  1. w 81"1*ͱ͸ʁ w άϩʔόϧύϥϝʔλ w ϖʔδωʔγϣϯ w ϑΟϧλʔ w ΧελϜ౤ߘλΠϓΛಠࣗΤϯυϙΠϯτͱͯ͠௥Ճ

    w ΧελϜϑΟʔϧυͷ௥Ճ w ೝূ w Ϣχοτςετ w ΫϥΠΞϯτϥΠϒϥϦʢ+BWB4DSJQUʣ
  2. ΦʔτσΟεΧόϦ $ http HEAD http://wp-api.test/wp-json/ HTTP/1.1 200 OK Access-Control-Allow-Headers: Authorization,

    Content-Type Access-Control-Expose-Headers: X-WP-Total, X-WP-TotalPages Allow: GET Connection: close Content-Type: application/json; charset=UTF-8 Date: Sat, 07 Oct 2017 23:16:58 GMT Link: <http://wp-api.test/wp-json/>; rel="https://api.w.org/" Server: Apache/2.4.18 (Ubuntu) X-Content-Type-Options: nosniff X-Robots-Tag: noindex 8PSE1SFTTʹؔ࿈͢ΔͳΜΒ͔ͷαʔϏεΛ։ൃ͢Δ৔߹͸ɺ ϨεϙϯεϔομʔͷA-JOLAΛνΣοΫʂ
  3. register_rest_route( 'rad/v1', 'site-info', array( array( 'methods' => 'GET', 'callback' =>

    function( $request ) { return array( 'phone_number' => get_option( 'phone_number' ), ); }, ), array( 'methods' => 'POST', 'callback' => function( $request ) { update_option( 'phone_number', $request['phone_number'] ); return array( 'phone_number' => get_option( 'phone_number' ), ); }, ), ) ); `register_rest_route()` Λ࢖ͬͯΦϦδφϧAPIΛ࡞Δྫ
  4. array( 'methods' => 'POST', 'callback' => function( $request ) {

    update_option( 'phone_number', $request['phone_number'] ); return array( 'phone_number' => get_option( 'phone_number' ), ); }, 'permission_callback' => function() { if ( current_user_can( 'manage_options' ) ) { return true; } return new WP_Error( 'rad_unauthorized', 'You do not have permission to update this resource.', array( 'status' => is_user_logged_in() ? 403 : 401 ) ); }, ), ೝূΛ͚ͭΔ৔߹͸ `permission_callback`
  5. add_action( 'rest_api_init', function() { register_rest_field( 'poi', 'poi', array( 'get_callback' =>

    function( $object ) { $meta = get_post_meta( $object['id'], '_addr', true ); return array( 'address' => $meta ); }, 'schema' => null, ) ); } ); ΧελϜϑΟʔϧυͷ஋͸σϑΥϧτͰ͸APIʹؚ·Ε·ͤΜɻ ʢηΩϡϦςΟ্ॏཁͳ৘ใؚ͕·ΕΔ͜ͱ͕૝ఆ͞ΕΔͨΊʣ ্ͷྫ͸ɺ`_addr` ͱ͍͏ΧελϜϑΟʔϧυͷ஋Λ `address` ͱ͍͏εΩʔϚͰAPIʹؚΊΔྫɻ