Featured image of post 【項目追加】Wordpress4.7で追加されたRestAPIのレスポンスにアイキャッチ画像のURLやサイズを追加するやり方【カスタマイズ方法】

【項目追加】Wordpress4.7で追加されたRestAPIのレスポンスにアイキャッチ画像のURLやサイズを追加するやり方【カスタマイズ方法】

1587文字

WordpressのAPIではアイキャッチが取れない

Wordpress4.7でRestAPIが追加

Wordpress4.7で追加された便利な機能として、投稿をREST APIで取得することが可能です。

WordPress はアプリケーションフレームワークへと生まれ変わろうとしています。このプロジェクトは、簡単で理解しやすく、信頼性の高い API フレームワークを開発することを目的として生まれました。そして WordPress 本体の API を開発することも目的としています。

このプラグインは簡単な HTTP ベースの REST API を提供します。あなたのサイトのユーザー、投稿、タクソノミー、その他のデータに対してシンプルな HTTP リクエストを送信することで、取り出したりアップデートすることが可能です。 WP REST API v2 Documentation

デフォルトで取得出来る情報は以下となっています。

/wp-json/wp/v2/posts/<post_id>
{
  "id": 6698,
  "date": "2018-10-21T18:00:47",
  "date_gmt": "2018-10-21T09:00:47",
  "guid": {
    "rendered": "https://blogenist/?p=6698"
  },
  "modified": "2018-12-05T17:55:25",
  "modified_gmt": "2018-12-05T08:55:25",
  "slug": "%e3%80%90%e6%82%aa%e5%a4%a2%e3%80%91%e3%83%9d%e3%82%b1%e3%83%a2%e3%83%b3go%e3%81%ae2018%e5%b9%b410%e6%9c%88%e3%81%ae%e3%80%8c%e3%83%80%e3%83%b3%e3%83%90%e3%83%ab%e3%82%b3%e3%83%9f%e3%83%a5%e3%83%8b",
  "status": "publish",
  "type": "post",
  "link": "https://blogenist/2018/10/21/6698/",
  "title": {
    "rendered": "【悪夢】ポケモンGoの2018年10月の「ダンバルコミュニティデイ」が通信エラー連発で中止になり、アイテムが無駄になった挙句、後日再実施になってしまった件【悲劇】"
  },
  "content": {
    "rendered": "<div>...</div>\n",
      "protected": false
  },
  "excerpt": {
    "rendered": "<p>...</p>\n",
    "protected": false
  },
  "author": 2,
  "featured_media": 6713,
  "comment_status": "closed",
  "ping_status": "closed",
  "sticky": false,
  "template": "",
  "format": "standard",
  "meta": {
    "amp_status": ""
  },
  "categories": [
    128
  ],
  "tags": [
    25,
    109,
    39,
    130,
    32,
    55
  ],
  "_links": {
    "self": [
      {
        "href": "https://blogenist/wp-json/wp/v2/posts/6698"
      }
    ],
    "collection": [
      {
        "href": "https://blogenist/wp-json/wp/v2/posts"
      }
    ],
    "about": [
      {
        "href": "https://blogenist/wp-json/wp/v2/types/post"
      }
    ],
    "author": [
      {
        "embeddable": true,
        "href": "https://blogenist/wp-json/wp/v2/users/2"
      }
    ],
    "replies": [
      {
        "embeddable": true,
        "href": "https://blogenist/wp-json/wp/v2/comments?post=6698"
      }
    ],
    "version-history": [
      {
        "href": "https://blogenist/wp-json/wp/v2/posts/6698/revisions"
      }
    ],
    "wp:featuredmedia": [
      {
        "embeddable": true,
        "href": "https://blogenist/wp-json/wp/v2/media/6713"
      }
    ],
    "wp:attachment": [
      {
        "href": "https://blogenist/wp-json/wp/v2/media?parent=6698"
      }
    ],
    "wp:term": [
      {
        "taxonomy": "category",
        "embeddable": true,
        "href": "https://blogenist/wp-json/wp/v2/categories?post=6698"
      },
      {
        "taxonomy": "post_tag",
        "embeddable": true,
        "href": "https://blogenist/wp-json/wp/v2/tags?post=6698"
      }
    ],
    "curies": [
      {
        "name": "wp",
        "href": "https://api.w.org/{rel}",
        "templated": true
      }
    ]
  }
}

上記はpost_id指定ですが、複数取得の場合は同様の配列形式で取得出来ます。

アイキャッチのURLが含まれていない。。。

デフォルトのレスポンスでは、記事内容に関する情報はおおよそ含まれているのですが、アイキャッチに関する情報が含まれていませんorz

他のブログやシステムからREST API経由で関連記事として表示したい場合に、アイキャッチ画像が取れないのは不便ですよね。。。

アイキャッチのURLが含まれていない。。。

しかし、WordpressのREST APIはとてもカスタマイズ性が高く、レスポンス項目を自由に拡張することが出来ますので、今回はREST APIへのアイキャッチ画像を追加する方法をご紹介致します♪

手順

functions.phpに追記

REST APIをカスタマイズするにはfunctions.phpにコードを追加する必要があります。

今回はアイキャッチ画像のURLとサイズを取得出来るようにしてみましょう。
以下を末尾に追記してください。

functions.php
//REST APIにアイキャッチ追加
add_action('rest_api_init', 'custom_wp_rest_api_post');
function custom_wp_rest_api_post() {
  register_rest_field('post',
    'featured_image',
    array(
      'get_callback' => 'rest_api_add_image',
      'update_callback' => null,
      'schema' => null,
    )
  );
}

function rest_api_add_image($object, $field_name, $request) {
  $feat_img_array = wp_get_attachment_image_src($object['featured_media'], 'large', true);
  return [
    'src' => $feat_img_array[0],
    'width' => $feat_img_array[1],
    'height' => $feat_img_array[2],
  ];
}

これは、rest_api_add_image関数で画像のsrc/width/height取得し、custom_wp_rest_api_post関数でregister_rest_field関数を使ってfeatured_imageという項目名でセットし、rest_api_initにアクションを追加しています。

確認

では、実際に再度叩いてレスポンスを確認してみましょう。

/wp-json/wp/v2/posts/<post_id>
{
  "id": 6698,
  "date": "2018-10-21T18:00:47",
  "date_gmt": "2018-10-21T09:00:47",
  "guid": {
    "rendered": "https://blogenist/?p=6698"
  },
  "modified": "2018-12-05T17:55:25",
  "modified_gmt": "2018-12-05T08:55:25",
  "slug": "%e3%80%90%e6%82%aa%e5%a4%a2%e3%80%91%e3%83%9d%e3%82%b1%e3%83%a2%e3%83%b3go%e3%81%ae2018%e5%b9%b410%e6%9c%88%e3%81%ae%e3%80%8c%e3%83%80%e3%83%b3%e3%83%90%e3%83%ab%e3%82%b3%e3%83%9f%e3%83%a5%e3%83%8b",
  "status": "publish",
  "type": "post",
  "link": "https://blogenist/2018/10/21/6698/",
  "title": {
    "rendered": "【悪夢】ポケモンGoの2018年10月の「ダンバルコミュニティデイ」が通信エラー連発で中止になり、アイテムが無駄になった挙句、後日再実施になってしまった件【悲劇】"
  },
  "content": {
    "rendered": "<div>...</div>\n",
    "protected": false
  },
  "excerpt": {
    "rendered": "<p>...</p>\n",
    "protected": false
  },
  "author": 2,
  "featured_media": 6713,
  "comment_status": "closed",
  "ping_status": "closed",
  "sticky": false,
  "template": "",
  "format": "standard",
  "meta": {
    "amp_status": ""
  },
  "categories": [
    128
  ],
  "tags": [
    25,
    109,
    39,
    130,
    32,
    55
  ],
  "featured_image": {
    "src": "https://blogenist/wp-content/uploads/2018/10/pokemongo10ResultEye.png",
    "width": 1116,
    "height": 610
  },
  "category": {
    "name": "ゲーム",
    "slug": "game"
  },
  "_links": {
    "self": [
      {
        "href": "https://blogenist/wp-json/wp/v2/posts/6698"
      }
    ],
    "collection": [
      {
        "href": "https://blogenist/wp-json/wp/v2/posts"
      }
    ],
    "about": [
      {
        "href": "https://blogenist/wp-json/wp/v2/types/post"
      }
    ],
    "author": [
      {
        "embeddable": true,
        "href": "https://blogenist/wp-json/wp/v2/users/2"
      }
    ],
    "replies": [
      {
        "embeddable": true,
        "href": "https://blogenist/wp-json/wp/v2/comments?post=6698"
      }
    ],
    "version-history": [
      {
        "href": "https://blogenist/wp-json/wp/v2/posts/6698/revisions"
      }
    ],
    "wp:featuredmedia": [
      {
        "embeddable": true,
        "href": "https://blogenist/wp-json/wp/v2/media/6713"
      }
    ],
    "wp:attachment": [
      {
        "href": "https://blogenist/wp-json/wp/v2/media?parent=6698"
      }
    ],
    "wp:term": [
      {
        "taxonomy": "category",
        "embeddable": true,
        "href": "https://blogenist/wp-json/wp/v2/categories?post=6698"
      },
      {
        "taxonomy": "post_tag",
        "embeddable": true,
        "href": "https://blogenist/wp-json/wp/v2/tags?post=6698"
      }
    ],
    "curies": [
      {
        "name": "wp",
        "href": "https://api.w.org/{rel}",
        "templated": true
      }
    ]
  }
}

正しくfeatured_image項目が追加されましたね♪

終わりに

上記のように必要な情報をREST API経由で取得するようにしておきえば、記事ごとに手入力する必要が無くなり、ショートコード等で自動化を図ることが出来ます。

WordpressのREST APIは使い勝手が良くかなり便利なので、是非触ってみてはいかがでしょうか♪