0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Vue.jsでWordPressの新着記事を取得

Last updated at Posted at 2020-03-12

WP REST API

WP REST APIっていうプラグインがある。
https://ja.wp-api.org/

「コレ何か?」っていうと

WordPressのデータをJSONで出すヤツです。

「コレの何が良いの?」といいますと

Webサイトのフロント側をWordPressテーマで作らなくても良いって事。

早速使ってみた。

フロントの作成は今回はVue.jsにします。
なんかGatsby.jsも良いんじゃないかなと最近思ったんですけど、
Reactの環境構築にハマってからまだ心の傷が癒えていないんで。

じゃあ新着記事を取得してみよう。
Wordpressの方は、プラグイン入れるだけって事で割愛して、

News.vue.js
<template lang="pug">
  .container-fluid(style="max-width:1000px;")
    .row
      .col-md-4(v-for="(wpAPI,i) in wpAPIs")
        .card
          a(:href="wpAPI.link")
            .card-img-wrap
              img.card-img-top( :src="wpAPI | image" alt="Card image cap")

            .card-body.textAlignLeft
              p.card-text.font-weight-bold {{ wpAPI.title.rendered | truncate(30) }}

              .wrapper
                a.card-link(:href="wpAPI._embedded['wp:term'][0][0]['link']") {{ wpAPI._embedded['wp:term'][0][0]['name'] | truncate(8) )}}

              .note.small
                | {{ wpAPI.date | dateFormatter}}
</template>

bootstrappugが入り混じっててカオスですが、まあこんな感じで。

News.vue.js
<style lang='stylus' scoped>
@import "./../../../../scss/_variable.styl"
p,div,li
  color $text-color
</style>

stylusで書いてるのにディレクトリがscssなのは特に意味はないです。

あと、「ディレクトリ深くほりすぎ」なんですが気にしないで下さい。
stylusってなんでComponentからの相対パスしか受け付けないんですかね??)

読み込んでるファイルの中にbootstrapreset.cssなどがある感じです。
(じゃあ名前_valiablesじゃないだろってツッコミがありそうですが)
まあサンプルなのでそこはゆるく行きましょう。。

News.vue.js
<script>
import axios from 'axios'
import Filters from '@/mixins/filters'
export default {
  name: 'News',
  mixins: [Filters],
  data:() => ({
    wpAPIs: [],
    apiserver: '',
  }),
  methods:{
    apiServer(){
      const self = this;
      self.apiserver = 'http://localhost:8001/wp-json/wp/v2/posts?_embed&per_page=12'
    },
    getJSON(){
      const self = this
      axios
        .get(
          self.apiserver, {
            headers:{ "Content-Type": "application/json" },
            data:{}
          }
        )
        .then(
          (response) => (
            self.wpAPIs = response.data
          )
        )
        .catch(
          (error) => {
            console.log(error);
          }
        );
    },
  },
  created(){
    const self = this
    self.apiServer();
    self.getJSON();
  },
}
</script>

{{ ○○ | truncate(24) }}とか{{ ○○ | dateFormatter}}とかでてきてるんですが、
これはVueのフィルター関数です、
「テキストを何文字以内に収める」とか、日時を「2020年3月12日と表示する」みたいな感じ。
割愛してますがmixinにまとめて収納してます。

axiosJSONを取得するのに使ってます。他にも色々あるらしいけど、
コレ使い方がいちばん簡単なのでオススメです。

apiServer()は、本番とローカルで切り替える予定なので、メソッドにおきます。
URLを決めたら→dataのapiserverに入れるっていう、、
ココ名前が似ててややこしいですね。。

created(){}datamethodsが読み込まれたタイミングです。
まだDOMは生成されていない段階ですね。ココがちょうど良いタイミングと思います。
ここでapiからデータを受け取り、wpAPIsに入れてます。

あとはvueのfor文であるv-forを使ってhtmlを書いていきます。
簡単にするとこんな感じです。

News.vue.js
.col-md-4(v-for="(wpAPI,i) in wpAPIs") //↓↓この中を繰り返し処理します
  a(:href="wpAPI.link")
    img(:src="wpAPI | image")
      a.card-link( :href= "wpAPI._embedded['wp:term'][0][0]['link']" )
        | {{ wpAPI._embedded['wp:term'][0][0]['name'] )}}
      .note.small
        | {{ wpAPI.date }}

{{ wpAPI | image}}っていうフィルターがあるんですが、
「なんで1記事の配列をまるごと受け取ってるんだよ。キモいな〜」と思うじゃないですか。
まあ、それにも理由がありまして、フィルター関数をご覧下さい。

filter.js
    image(index) {
      if(index['_embedded']['wp:featuredmedia'] !== undefined){
        const value = index['_embedded']['wp:featuredmedia'][0].source_url;
        return value;

      }else if(index['_embedded']['wp:featuredmedia'] == undefined){
        const value2 = index['content']['rendered'].match(/<img[^>]+>/gi);
        const url = value2[0].match(/src=["|'](.*?)["|']/)[1];
        return url;

      }else{
        return '/common/img/noimage.png';
      }
    },

お分かりいただけただろうか?
記事を書いてる人が「サムネイル画像」を投稿内容に設定していない時は
「記事に貼り付けてある一番最初の画像を取ってくる」という面倒くさい事を
やっているのです。

これで新着記事を、Bootstrapのカード的な感じで、
Vue.jsで表示できるようになります。

多分SEOを重視した方が良い的な要件があると思うので、本来は
Nuxt.jsGatsby.jsなんかで、実装した方が良いかなと漠然と思います。

つぎはGatsby.jsかな〜。日本で流行るか知らんけど。
以上です。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?