There are 4 seasons in my Wordpress template. Each season has a start and end date.
This is my current date:
$currentDate = date('d-m') . '-' . date('Y');
$currentDate = date('d-m-Y', strtotime($currentDate)); //output 16-05-19
Example of season 1 start and end date:
$season_1_start = get_sub_field('start_date','option');
$season_1_start = date('d-m-Y', strtotime($season_1_start));
$season_1_end = get_sub_field('end_date','option');
$season_1_end = date('d-m-Y', strtotime($season_1_end));
The output of the season dates is also 'd-m-Y'.
How can I check if $currentdate
is between $season_1_start
and $season_1_end
So:
if (($currentDate >= $season_1_start) && ($currentDate <= $season_1_end)){
echo "season 1";
}
if (($currentDate >= $season_2_start) && ($currentDate <= $season_2_end)){
echo "season 2";
}
if (($currentDate >= $season_3_start) && ($currentDate <= $season_3_end)){
echo "season 3";
}
if (($currentDate >= $season_4_start) && ($currentDate <= $season_4_end)){
echo "season 4";
}
But my output is season 1season 2season 3season 4
So it seems that every if statement is true.
I've already checked if the season dates are correct and I don't see anything wrong with them.
The result should be, today, season 2
I'm not well versed with WordPress, but seems like something you can easily solve in plain PHP.
You can use the DateTime class to compare against the current date today. Since your format isn't standard, we can use DateTime::createFromFormat()
. This creates a DateTime object based on the format you provide - which in your case is d/m
. Since no year is specified, it uses the current year.
You might need to adjust the conditions to >=
or <=
, depending on what dates your ranges are defined within.
$today = new DateTime;
$season_1_start = DateTime::createFromFormat("d/m", get_sub_field('start_date','option'));
$season_1_end = DateTime::createFromFormat("d/m", get_sub_field('end_date','option'));
if ($today > $season_1_start && $today < $season_1_end) {
// Season 1
}
Then do the same for your other seasons.