We recently built a wild bird food products web site where the site owner wanted to display a summer image of birds on a bird feeder during the warm months, but automatically substitute a Christmas bird feeder image during the November and December Christmas holiday season, and then a winter shot during the following winter months. In this PHP tutorial I thought I would share our solution for others to use.
This script can be modified for any number of date ranges during the year. The script works by using a default image name that in this case displays during the summer months. During specified date ranges, other image files names are substituted. All of the images must be the same dimensional size for this to work.
You can set this up with any number of special holiday images. Each can be set to display between any date ranges.
This PHP solution is easy to understand and easy to modify. There are a number of ways to accomplish the same goal with PHP, but this method is elegant in its simplicity. Even a novice PHP programmer should be able to understand how it works.
<?php $seasonalPix = "bird-feeder-summer.jpg"; $todaysDate = date("Y-m-d"); $holidayStart1 = date("Y")."-11-01"; $holidayEnd1 = date("Y")."-12-31"; $winterStart2 = date("Y")."-01-01"; $winterEnd2 = date("Y")."-03-31"; if (($todaysDate >= $holidayStart1) AND ($todaysDate <= $holidayEnd1)) { $seasonalPix = "bird-feeder-christmas.jpg"; } if (($todaysDate >= $winterStart2) AND ($todaysDate <= $winterEnd2)) { $seasonalPix = "bird-feeder-winter.jpg"; } ?> <img src="/images/<?php echo $seasonalPix; ?>" width="250" height="338" class="alignleft" alt="bird feeder" />
Here is how it works.
Line 2 loads a variable with the image file name for the default image. In this case, it is the summer shot of the bird feeder loaded with birds.
Line 3 sets up today’s date in a format that is easy to use for comparison to other dates.
Lies 5 and 6 set the start and end dates for November and December.
Lines 8 and 9 set the start and end dates for January, February and March.
Lines 11 through 14 checks to see if today’s date falls withing the range specified for November and December. If it does, the Christmas bird feeder file name is substituted for the default file name.
Lines 15 through 18 checks to see if today’s date falls withing the date range for the remaining winter months. If it does, the winter bird feeder image file name is substituted for the default image file name.
Line 22 shows how to use the embedded PHP code withing the HTML image tag.
This script can also be modified to substitute text messages during different times of the year.