What's the Current Year II

Controlling page content based on the year

In the previous article, we looked at how to get and display the current year with a snippet. In this one, well see some ways to control the content on a page based on the year.

MODX logo

The Problem

Suppose that you have a chunk tag that inserts a bit of text, but the text should change on January first. It might be a price list, for example, where you want the new prices to appear on January first.

The Solution

The secret is to name your chunks based on the year (e.g., 2019 and 2020). It's a good practice to add a text prefix to the chunk name in case you later want to use other year-related chunks (e.g. pricelist2019 and pricelist2020).

Now, you can put this tag where you want the price list to appear:


Then, create a snippet called PriceList with this code:

/* PriceList snippet */
$year = date("Y");
return $modx->getChunk('pricelist' . $year);

The prices will change automatically when the new year starts. The argument to getChunk() simply concatenates the string "pricelist" and the year.

Note that for future years, all your have to do is add a new chunk named for the year.

Coming Up

In the next article, we'll look at a way to forward users to different places based on the current year.

Looking for high-quality, MODX-friendly hosting? As of May 2016, Bob's Guides is hosted at A2 hosting. (More information in the box below.)

Comments (0)

Please login to comment.