まだ触りたてですが、ちょっとだけハマったのでメモ。
試す
wp rest apiをインストール
ドキュメントも上のサイトで兼ねています(あんまり読んでない。。。)
インストールしたら、下記URLにアクセスしてみてください。私はcurl
を使いました。
$ curl http://localhost/wp-json/ | jq % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 41393 0 41393 0 0 144k 0 --:--:-- --:--:-- --:--:-- 145k { "name": "wordpress title", "description": "Just another WordPress site", ...
色々わぁーってでてこればおk.
この時、.htaccess
とかでrewrite
が効いていないとうまくいきませんので注意。
カスタム投稿タイプを引っ張ってくる
これもちょっとハマった。
検索してすぐでてくる下のサイトを参考にしましたが、うまくいかなかった。
$ curl http://localhost/wp-json/v2/wp/my-custome-post | jq % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 226 100 226 0 0 821 0 --:--:-- --:--:-- --:--:-- 824 { "code": "rest_no_route", "message": "URLとリクエストメソッド(request method)に合ったルートがありません", "data": { "status": 404 } }
うまくいったコードは下のURLの記事を参考にしました。
- functions.php
<?php /** * アドバンスカスタムフィールドを wp rest apiで使用する */ function wp_rest_api_alter() { $params = array( 'get_callback' => function ($data, $field, $request, $type) { if (function_exists('get_fields')) { return get_fields($data['id']); } return []; }, 'update_callback' => null, 'schema' => null, ); register_api_field('my-custom-post', 'fields', $params); } add_action('rest_api_init', 'wp_rest_api_alter'); /** * wp rest api でカスタム投稿タイプを使うための記述 */ function sb_add_cpts_to_api() { global $wp_post_types; $key = 'my-custom-post'; $wp_post_types[$key]->show_in_rest = true; $wp_post_types[$key]->rest_base = $key; } add_action('init', 'sb_add_cpts_to_api', 30);
テーマのfunctions.php
に書き込めばうまくいきました。
前、自分でAPI作ってみたけど、こっちのが全然よさそうなので、こっちを使うことにします。
そういえばセキュリティとかこれどうなんだろ?