🌲 WP REST API にカスタムのAPIを生やす

2020-12-30 /Development
この記事は最終更新日から2年以上経過しています。

WP REST APIではデータは現状最大で100件までしか返ってこないのですが、Next.jsやNuxt.jsなんかを使用して静的サイトを構築する場合には都度ページごとに読み込んでもいられないので、カスタムした API を作成して一気に呼び出すのが良さそうです。

というのがあって色々試してみたのですが、後から使う事があった時のためにメモ。

api.php(functions.php に読み込む):

コピーしました
function custom_api_get_info()
{
  register_rest_route('custom/v1', '/info', array(
    'methods' => 'GET',
    'callback' => 'custom_api_get_info_callback'
  ));
}
add_action('rest_api_init', 'custom_api_get_info');

function custom_api_get_info_callback($request)
{
  $info = array();

  //全タグを取得して格納したり
  $info['tags'] = get_all_tags();

  //全記事数を格納したり
  $info['published'] = wp_count_posts()->publish;

  //全記事取得をそのまま取得したい場合とかにはこっち
  $info['posts'] = get_all_posts();

  //カスタム投稿やカスタムフィールドはacfを利用
  // (「投稿タイプの追加と編集」から「REST API で表示」をtrueにする必要有)
  $info['xxx'] = get_all_xxx();

  return $info;
}

//全タグを取得する関数
function get_all_tags()
{
  $re = array();
  $items = get_tags();
  foreach ($items as $item) {
    $re[] = (object) array(
      'name' => $item->name,
      'slug' => $item->slug,
      'count' => $item->count,
      'term_id' => $item->term_id,
    );
  }
  return $re;
}

//全投稿を取得する関数
function get_all_posts()
{
  $re = array();
  $posts = get_posts(array(
    'posts_per_page' => -1
  ));
  foreach ($posts as $post) {
    $id = $post->ID;
    $re[] = (object) array(
      'id' => $id,
      'slug' => $post->post_name,
      'title' => $post->post_title,
      'content' => $post->post_content,
    );
  }
  return $re;
}

//カスタム投稿タイプ xxx や、カスタムフィールド `xxx_text`などを取得する関数
function get_all_xxx()
{
  $re = array();
  $posts = get_posts([
    'posts_per_page' => -1,
    'post_type' => 'xxx'
  ]);
  foreach ($posts as $post) {
    $acf = array('acf' => (array) array(
      'xxx_text' => get_field('xxx_text', $post->ID)
    ));
    $re[] = (object) array_merge((array) $post, (array) $acf);
  }
  return $re;
}

APIを生やしたら curl でチェックしてみる

コピーしました
$ curl http://localhost:8000/wp-json/custom/v1/info | jq

なるべくなら自分でコード書くよりも ACF to REST API を入れるのが良さそうなんだけど、ちょっと別の値を引っ張ってきたいときなどに必要になりそうです。

Comment
comments powered by Disqus
Profile

石原 悠 / Yu Ishihara

デザインとプログラミングと編み物とヨーグルトが好きです。