Im not great at PHP but I typed up the following code to change the header image based on the date array I have set.
Im wondering if the code looks alright and will function as intended or if iv missed something in my coding.
$hollidayevents = array(
array(
'image' => 'wp-content/uploads/1.png',
'start' => '01-02',
'end' => '02-02'
),
array(
'image' => 'wp-content/uploads/2.png',
'start' => '03-02',
'end' => '04-02'
)
);
foreach($hollidayevents as $myevent) {
if(date('d-m') >= $myevent['start'] && date('d-m') <= $myevent['end']) {
echo "<img src='".$myevent['image']."'>";
}
else { echo "<img src='wp-content/uploads/default header image'>";}
}
CodePudding user response:
When you compare the dates as string with 'd-m' format the result is based on the day and only if days are same then it comes to compare months too.
For example imagine this: '20-10' > '01-11'
, both are with format you used 'd-m'
what is the result ? First is higher then second so the result is true, even tho you would expect the opposite. Thats because only first character gets compared.
$hollidayevents = array(
array(
'image' => 'wp-content/uploads/1.png',
'start' => '02-01', // <- m-d format
'end' => '02-02' // <- m-d format
),
array(
'image' => 'wp-content/uploads/2.png',
'start' => '02-03', // <- m-d format
'end' => '02-04' // <- m-d format
)
);
$eventFound = false;
foreach($hollidayevents as $myevent) {
if(date('m-d') >= $myevent['start'] && date('m-d') <= $myevent['end']) {
echo "<img src='".$myevent['image']."'>";
$eventFound = true;
break;
}
}
if(!$eventFound){
echo "<img src='wp-content/uploads/default header image'>";
}