LoginSignup
6

More than 3 years have passed since last update.

【AMP】amp-listでWP REST APIを使って記事リストを取得する

Last updated at Posted at 2017-09-16

モバイルWebの進化の象徴とも言えるのが「AMP」や「PWA」

AMP(Accelerated Mobile Pages)とはモバイルサイトを高速表示するためのプロジェクト、もしくはそのためのフレームワーク(AMP HTML)のことです。

AMPは、ページをあらかじめGoogleやTwitter側でコンテンツをキャッシュする(AMP CDN)ことで、物理的にアクセスにかかる時間を削減し、またCSSのインライン化、画像の遅延遅延ロード、JavaScriptの実行制限等で、ハイパフォーマンスなモバイルサイトを実現しています。

ここでは、そんなAMPの拡張コンポーネントの1つである「amp-list」で、WP REST APIを使いWordpressに投稿されている記事の一覧を取得して、AMP化されたサイトに表示する方法を紹介します。

スクリーンショット 2017-09-16 19.42.00.png

http://demo.wp-api.org/
というWPのデモサイトから記事リストを取得します。

JQueryやvue.jsやReact.js、AngularJSといったJSフレームワークは一切使いません。
HTMLのみでそれを実現します。

amp-listとは?

AMPの拡張コンポーネントです。amp-listは、CORS JSONエンドポイントから動的コンテンツを取得し、提供されたテンプレートを使用してレンダリングを行います。動的リストなどを埋め込むのに適しています。

使い方はamp-listコンポーネントをインポートします。

<script async custom-element="amp-list" src="https://cdn.ampproject.org/v0/amp-list-0.1.js"></script>

...とamp-mustacheをヘッダ内に挿入

<script async custom-template = "amp-mustache"  src = "https://cdn.ampproject.org/v0/amp-mustache-0.1.js" ></ script >

サンプル

ベースのAMPサンプルにamp-listを実装しました。


<!doctype html>
<html amp lang="en">
  <head>
    <meta charset="utf-8">
    <title>Hello, AMPs</title>
    <link rel="canonical" href="http://example.ampproject.org/article-metadata.html">
    <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1">
    <script type="application/ld+json">
      {
        "@context": "http://schema.org",
        "@type": "NewsArticle",
        "headline": "Open-source framework for publishing content",
        "datePublished": "2015-10-07T12:02:41Z",
        "image": [
          "logo.jpg"
        ]
      }
    </script>
    <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
    <style amp-custom>
      /* any custom style goes here */
      body {
        padding: 10px;
      }
      h1 {
        text-align: center;
      }
    </style>
    <script async src="https://cdn.ampproject.org/v0.js"></script>
    <script async custom-element="amp-list" src="https://cdn.ampproject.org/v0/amp-list-0.1.js"></script>
    <script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.1.js"></script>
  </head>
  <body>
    <h1>amp-list</h1>
    <amp-list width="auto"
      height="400"
      layout="fixed-height"
      src="https://demo.wp-api.org/wp-json/wp/v2/posts"
      class="m1"
      items=".">
      <template type="amp-mustache">
        <div>
          <a href="{{link}}">{{title.rendered}}</a>
        </div>
      </template>
    </amp-list>
  </body>
</html>

全体的にはこんな感じです。
amp-listは以下の部分になります。


<amp-list width="auto"
   height="400"
   layout="fixed-height"
   src="https://demo.wp-api.org/wp-json/wp/v2/posts"
   class="m1"
   items=".">
   <template type="amp-mustache">
     <div>
       <a href="{{link}}">{{title.rendered}}</a>
     </div>
   </template>
</amp-list>

{{title.rendered}} に、返ってくるJSONにある記事タイトルが、
{{link}} に記事URLが入ります。

src属性

src属性は、レンダリングされるJSONを返すリモートエンドポイントのリクエストURLを設定します。

今回はWordpressのデモサイトから記事リストを取得するので、URLはhttps://demo.wp-api.org/wp-json/wp/v2/postsとなります。

基本的にCORS HTTPサービスでなければなりません。さらにURLのプロトコルはHTTPSである必要があります。

src="https://demo.wp-api.org/wp-json/wp/v2/posts"

items属性

ここは重要なポイントです。
リクエスト内でレンダリングされる配列を特定する式を定義します。
JSONレスポンスのフィールドを介してナビゲートするドット表記の式です。

リクエスト自体が目的の配列であれば値は "."

指定がなければ、デフォルトは items ですが、以下のような配列でなければなりません。

{ 
  "items":[...] 
}

WP REST APIで返ってくるJSON配列は接頭辞ないので、"." となります。

確認しましょう

スクリーンショット 2017-09-16 19.42.00.png

うまく記事一覧を取得&表示できています。
記事タイトルのリンクをクリックすれば、デモサイトの記事ページに飛びます。

件数を絞りたいときは・・・

WP REST APIの話になりますが、リクエストURLにクエリパラメータで?per_page=2を付与すれば、2件に絞れます。

src="https://demo.wp-api.org/wp-json/wp/v2/posts?per_page=2"

スクリーンショット 2017-09-16 21.49.06.png

まとめ

さらに驚くことに、src属性で ?clientId=CLIENT_ID(myCookieId)" などのパラメータを付け、パーソナライズされた関連コンテンツを取得できたりもします。

amp-formやamp-bindを使えばCRUDもいけるじゃないかと(まだやってない)

いかがでしたでしょうか?
JavaScriptがなくてもWP REST APIを使えるんです。
Webフロントエンドの未来は明るいですね。

参考

amp-list 公式リファレンス(英語) by Google
https://www.ampproject.org/docs/reference/components/amp-list

WP REST API 公式リファレンス(日本語)
http://ja.wp-api.org/

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
6