Craft CMS で月別アーカイブを実装する

Craft CMS で月別アーカイブを実装する方法をご紹介します。

Craft CMS Logo

今回は Craft CMS で、2017 年 12 月の記事一覧ページを、 /blog/2018/12 という URL で表示したいとします。

Rooting の設定

Dynamic Routes を参考に Rooting を設定します。リンク先にも書いてありますが、ここでの設定は / スラッシュで始まらないようにしましょう。

テンプレートを実装

先程 Add a token のところで入れた yearmonth などは、テンプレートの中でそのまま yearmonth という変数に値が入ってきます。

それを前提にして月別アーカイブを実装すると下記のようになります。

{% set from = year ~ '-' ~ month ~ '-' ~ '01' %}
{% set to =( from | date_modify('+1 month')) | date('Y-m-d') %}
{% set entries = craft.entries.section('blog').limit(null).after(from).before(to) %}
{% for entry in entries %}
    {% if loop.first %}
        <h2>{{ year }}年{{ month }}月</h2>
        <ul>
    {% endif %}
    <li>{{ entry.title }}</li>
    {% if loop.last %}
        </ul>
    {% endif %}
{% endfor %}

上記のコードでは、まず、

{% set from = year ~ '-' ~ month ~ '-' ~ '01' %}

で、取得した「年( from )月( month )」の 1 日を from にセットするして 2017-12-01 という形にします。そして、

{% set to =( from | date_modify('+1 month')) | date('Y-m-d') %}

で、まず (from | date_modify('+1 month'))from の 1 ヶ月後を取得し、 | date('Y-m-d') で 2018-01-01 の形の文字列にして to にセットします。最後に、

{% set entries = craft.entries.section('blog').limit(null).after(from).before(to) %}

afterfrom を、 beforeto を渡してその範囲内のエントリを取得します。

エントリの絞込に関しては下記の記事がとても参考になるのでご覧ください。

以上です。

Published 2018-01-23
Updated 2024-04-10