Jump to content

How do I retrieve all pages within a certain month/year?


ryan
 Share

Recommended Posts

I am especially interested in how I might get year/month get vars (or URL segments?) and what an example query /code would look to fetch those pages.

Here's a function that would return all the children in a month. Replace the last param ($field) with the name of the date field you want it to look at, otherwise it defaults to the 'modified' field, which probably isn't what you want (but was what I used to test the function).

<?php
/**
* Return all of the page's children where $field falls in $month and $year.
*
* @param Page $page The page that has the children we are finding.
* @param int $month Month you want to match.
* @param int $year Year you want to match.
* @param string Name of the date field to check.
* @return PageArray All the matching children.
*
*/
function childrenInMonth($page, $month, $year, $field = 'modified') {
    $startTime = strtotime("$month/1/$year");
    $endTime = strtotime("next month", $startTime);
    return $page->children("$field>=$startTime, $field<$endTime, sort=$field");
}

Below is an example of how you might use this function in your template. This code shows examples for both URL segments and GET vars. If you wanted to use URL segments, you would need to go in to the Admin CP, click on Setup > Templates > Your Template > Advanced > URL Segments > Set it to an asterisk "*". That tells it to allow any URL segments to pages using that template. And here is code that first checks for a URL segment, then GET vars, and defaults to current month/year if none is provided.

<?php

if($input->urlSegment1 && preg_match('/^(\d{4})-(\d{1,2})$/', $input->urlSegment1, $matches)) {
    // A URL segment matched in the format of year-month, i.e. /news/2010-12
    $month = $matches[2];
    $year = $matches[1];

} else if($input->get->month && $input->get->year) {
    // GET vars were provided with the year and month
    $month = (int) $input->get->month;
    $year = (int) $input->get->year;

} else {
    // No year/month provided, so display items from current month
    $month = date('m');
    $year = date('Y');
}

// display a headline with selected month/year
echo "<h2>" . date('F Y', strtotime("$year-$month")) . "</h2>";

// find the matching pages
$children = childrenInMonth($page, $month, $year);

// output a list of the matching pages
echo "<ul>";
foreach($children as $child) {
    echo "<li><a href='{$child->url}'>{$child->title}</a></li>";
}
echo "</ul>";

  • Like 3
Link to comment
Share on other sites

  • 2 years later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...