Filter Posts By Month

The following examples will show you how to display Posts on the website based on their month.
For instance, you may have a sidebar in your design that shows an archive of articles:


This can be helpful for visitors to quickly see posts from the past months or years.

This article makes use of the function: \Components\Website\Posts::filtersForMonths()

To change the Date of a Post, navigate to Dashboard > Website > Posts, click a Post to edit, and select the "additional attributes" tab. 

From Within Your Design

Step One:
Use an <data:repeater> to retrieve posts that are published within the given range of months. In the example below, we are retrieving all posts that are published from September 2017 to September 2020:

<ul> <data:repeater datasource="\Components\Website\Posts::filtersForMonths(36)" as="filter"> </data:repeater> </ul>


Step Two:
Add an <logic:if> control, to check the number of posts for a given category. In the example below, we will display all the months within the given range and the number of posts that are published on a particular month. 

<ul> <data:repeater datasource="\Components\Website\Posts::filtersForMonths(36)" as="filter"> <logic:if test="\Components\Website\Posts::getCountForCategory(12, $filter['filter'])"> <li> <a href="/news/?date_start=[? $filter['date_start'] ?]&date_end=[? $filter['date_end'] ?]"> [? $filter['month'] ?] ([? \Components\Website\Posts::getCountForCategory(12, $filter['filter']) ?]) </a> </li> </logic:if> </data:repeater> </ul>

This code will display all months that have published posts. It will also show the numbers of posts within the month.

Filter the Post Repeater

On the page where the post repeater is, add a PHP function for the datafilter
This function uses the month from the URL query string and builds a filter.

PHP Function

<?php function getDateFilter() { $arrFilter = []; if (isset($_GET['date_start'])) { $arrFilter[] = ['post_date', '>=', $_GET['date_start']]; } if (isset($_GET['date_end'])) { if ($arrFilter) $arrFilter[] = 'AND' $arrFilter[] = ['post_date', '<', $_GET['date_end']]; } return $arrFilter; } ?>

Add DataFilter to the Repeater

<data:postrepeater paging="true" datafilter="[? getDateFilter() ?]" />