LoginSignup
2
4

More than 3 years have passed since last update.

WordPressのREST APIにアイキャッチ画像のURLを追加する

Posted at

WordPressのREST APIでアイキャッチ画像のURLを取得して表示しようとしたら画像のIDしか返ってこなくて微妙だったのでURLが返ってくるようにカスタマイズしたメモ。

環境

  • WordPress 5.5.1
  • PHP7.4.0

コード

functons.php
add_action('rest_api_init', 'customize_api_response');
function customize_api_response() {
  // アイキャッチ画像のレスポンスを追加する投稿タイプ
  $post_types = ['hoge', 'fuga'];

  foreach ($post_types as $post_type) {
    register_rest_field(
      $post_type,
      'thumbnail',
      array(
        'get_callback'  => function ($post) {
          $thumbnail_id = get_post_thumbnail_id($post['id']);

          if ($thumbnail_id) {
            // アイキャッチが設定されていたらurl・width・heightを配列で返す
            $img = wp_get_attachment_image_src($thumbnail_id, 'large');

            return [
              'url' => $img[0],
              'width' => $img[1],
              'height' => $img[2]
            ];
          } else {
            // アイキャッチが設定されていなかったら空の配列を返す
            return [];
          }
        },
        'update_callback' => null,
        'schema'          => null,
      )
    );
  }
}

これでAPIのレスポンスに下記のように thumbnail という項目が含まれるようになりました。

thumbnail: {
  url: "https://xxxxxxxxxx.jpg",
  width: 900,
  height: 600
}

追記

https://xxxxx/wp-json/wp/v2/posts?_embed のようにパラメータに _embed をつけたら取得できるようになると教えてもらいました。
が、かなり階層の深いところに取りにいかないといけないようです。

2
4
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
2
4