LoginSignup
3
3

More than 1 year has passed since last update.

wordpressカスタム投稿タイプの REST API 使い方

Last updated at Posted at 2020-09-14

WordPress REST API 設定する

Custom Post Type UIの場合

Custom Post Type UIでカスタム投稿を登録している場合は特に設定は不要です。
(デフォルトでtrueになってます)

直接function.phpで作成している場合

まず、function.phpで作成しているカスタム投稿に WordPress REST API が使えるように許可します。
'show_in_rest' => true, 引数を追加します。
ここ重要でデフォルトがfalseですのでtrueにしないと WordPress REST API データを返してくれません。

WordPress REST API に関係する引数一覧

引数
show_in_rest デフォルトfalse
rest_base URLのベースとなる名前。基本省略(省略時カスタム投稿タイプ名)
rest_controller_class 処理するコントローラ名。基本省略(省略時WP_REST_Posts_Controller)
function.php

add_action('init', 'init_news');

function init_news(){
    $labels = array(
        'name' => _x('NEWS', 'post type general name'),
        'singular_name' => _x('NEWS', 'post type singular name'),
        'all_items' => 'NEWS一覧',
        'add_new' => _x('新規登録', 'news'),
        'add_new_item' => __('NEWSを登録'),
        'edit_item' => __('NEWSを編集'),
        'new_item' => __('新しいNEWS'),
        'view_item' => __('NEWSページを表示'),
        'search_items' => __('NEWSを探す'),
        'not_found' =>  __('NEWSはありません'),
        'not_found_in_trash' => __('ゴミ箱にNEWSはありません'),
    );
    $args = array(
        'labels' => $labels,
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'query_var' => true,
        'rewrite' => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'show_in_rest' => true,
        'supports' =>  array('title','editor'),
        'has_archive' => true
    );
    register_post_type('news',$args);
}

独自エンドポイントを設定する

そして独自エンドポイントを設定します。
自由にカスタマイズできますが、基本的には下記のように書けば動きます。
ループで取得したデータをレスポンスデータ配列($data[ ])に入れます。

※カスタムフィールドもここで取得できます。
(これでフロンド側で取得出来るようにJSONファイルが出来上がります。)

エンドポイントの例↓

function.php
add_action('rest_api_init', 'add_custom_endpoint');

function add_custom_endpoint() {
  register_rest_route('custom/v1', '/news', array(
    'methods' => 'GET',
    'callback' => 'news_api',
  ));
}

function news_api(WP_REST_Request $request) {
  $args = array(
    'post_type' => 'news',
    'order' => 'DESC',
    'post_status' => 'publish',
  );

  $the_query = new WP_Query($args);
  $data = array();
  while ($the_query->have_posts()) {
    $the_query->the_post();

    // カスタムフィールド取得方法↓
    $section = get_field('section', get_the_ID());

    // レスポンスデータ
    $data[] = array(
      'id' => get_the_ID(),
      'date' => get_the_date('Y.m.d', get_the_ID()),
      'title' => get_the_title(),
      'link' => get_the_permalink(),
    );
  }

  // レスポンス
  $response = new WP_REST_Response($data);
  $response->set_status(200);
  return $response;
}

register_rest_route( 'custom/v1', '/news', array());
を変更する下記の箇所がカスマイズ出来ます。
localhost/wp-json/custom/v1/news
※WPが直下に展開されている場合(違うフォルダの場合はフォルダのパスが必要)
例)localhost/WPフォルダまでのパス/wp-json/custom/v1/news

権限をつけたい時

特にPOSTなどは実行するには認証を必要としたい場合が多いと思う。
そういう時には、実行前に権限をチェックする関数を呼び出すものとして、permission_callbackが用意されている。
register_rest_routeの第三引数の中で以下のように指定する。

function.php
register_rest_route( 'custom/v0', '/create', array(
  'methods' => 'POST',
  'permission_callback' => 'create_permissions_check',
  'callback' => 'create_item'
) );

この呼びだされた関数で、trueを返すと通り、falseを返すとエラーとなる。

この権現の確認は、current_user_can関数で行う。

function.php
function create_permissions_check(){
  return current_user_can('publish_posts');
}

最後に

JSONファイルが出来上がりますので確認。
下記のようにドメインの後に追加してアクセスして見てください。
http://localhost/wp-json/custom/v1/news

rest_base項目を設定するとURLを変えることが出来ます。
rest_base => 'base'
http://localhost/wp-json/custom/v1/base

JSONファイルが見えたら終わりです。
後は、フロンド側で自由にやりたいように整形すれば完了です。

Chromeの拡張機能でJSONが見やすくなりますのでオススメです。
JSONView
https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc

参考サイト
https://www.tam-tam.co.jp/tipsnote/cms/post9688.html

リファレンス
https://developer.wordpress.org/rest-api/
https://wp-rest-api.mydocument.jp/

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3