This is a handy script for managing an out of office message on your website. I find this very useful on business websites when you’re tired of making that one little change to let people know when the office will be shut down. With about 15 minutes of extra work, you only need to do it once a year.
Let’s say for instance we’re doing all of the major U.S. Holidays in 2010, observing weekend Holidays with a day off on either side of the weekend. This means first we need to determine what those dates are. I just happen to have looked up the six most common, listed below:
- New Year’s Eve – January 1st
- Memorial Day – May 31st
- Independence Day – July 5th (July 4th is Sunday)
- Labor Day – September 6th
- Thanksgiving – November 25th and 26th
- Christmas – December 24th (December 25th is a Saturday)
Now that we know our dates, we can build them into an array:
$date_array = array(
"New Yearís Eve" =>
array("leaving" => "2010-12-31", "returning" => "2011-01-03"),
"Memorial Day" =>
array("leaving" => "2010-05-31", "returning" => "2010-06-01"),
"Independence Day" => // July 4th is a Sunday
array("leaving" => "2010-07-05", "returning" => "2010-07-06"),
"Labor Day" =>
array("leaving" => "2010-09-06", "returning" => "2010-09-07"),
"Thanksgiving" =>
array("leaving" => "2010-11-025", "returning" => "2010-11-029"),
"Christmas" => // December 25th is a Saturday
array("leaving" => "2010-12-24", "returning" => "2010-12-27"),
);
The date array can easily be stored in a database or be made up of more complicated functions that would calculate the holidays across multiple years with some basic logic. Maybe we’ll cover the latter part in another post some day.
Now we need to build the function itself. This function will be run every time the page loads. You can even include the function in a separate file to be included on multiple pages:
function holiday_message($date, $date_array) {
$date = strtotime($date); // Reformat the date so we can do math on it.
foreach($date_array as $key => $value) {
$leaving = strtotime($value['leaving']);
$returning = strtotime($value['returning']);
$early_warning = $leaving - 86400 * 7;
// If the date is between (7 days before) leaving and returning
if($date > $early_warning && $date < $returning) {
echo
"We will be observing ".$key." from ".date("Y-m-d", $leaving).
" until ". date("Y-m-d", $returning).".
When we return we will be more than happy to assist you.";
}
}
}
Now we just need to execute this function anywhere on the page:
holiday_message(date("Y-m-d H:i:s"),$date_array);
This code can be customized in numerous different ways, so the the message is more formal, or works for your specific situation. You can also change the way days are stored or calculated, like the example above. This is a core to get you started. Where can you go from here?