I'm working on a countdown timer that shows the amount of days remaining until a given enddate. It's a fairly simple and straightforward function that compares the current date with a date in the future with a simple PHP function: $currentDate->diff($endDate);
.
This function works on the homepage but breaks when another one is added to a different page. The timer on the homepage will still work but the others end up being completely off. The homepage timer could have "50 days remaining" while the one on, let's say, the About page has "52 days remaining".
This is the PHP placed in the header of the website (Wordpress) that handles everything:
<?php if( $fields['temp_offer'] ) { ?>
<div class="svc-content_right">
<?php
date_default_timezone_set('Europe/Amsterdam');
foreach( $fields['temp_offer'] as $timer ) { ?>
<?php // Countdown timer
$startTimeStamp = new DateTime($timer['startdate']);
$currentTimeStamp = new DateTime(date("Y-m-d"));
$endTimeStamp = new DateTime($timer['enddate']);
$numberDays = $currentTimeStamp->diff($endTimeStamp);
if( $timer['startdate'] && $timer['enddate'] ) {
if( $currentTimeStamp >= $startTimeStamp && $currentTimeStamp < $endTimeStamp) { ?>
<a href="#">
<div class="temp-offer_block">
<div class="temp-offer_title">
<?php echo $timer['offer'] ?>
</div>
<div class="countdown-timer">
<?php if($numberDays->format('%a') <= 1) {
printf(__('<small>Only </small><span>%s</span> <small>Day left</small>', 'cr-events'), $numberDays->format('%a'));
} else {
printf(__('<small>Only </small><span>%s</span> <small>Days left</small>', 'cr-events'), $numberDays->format('%a'));
} ?>
</div>
</div>
</a>
<?php } ?>
<?php } ?>
<?php } ?>
</div>
<?php } ?>
$startTimestamp
is an option to pass a date on which the countdown timer is made visible on the site. $currentTimestamp
is the current date in the same format as the start- and enddate. $endTimestamp
is the given enddate which is used in the calculation. Lastly $numberDays
is a PHP function to calculate the amount of days between two dates ($currentTimestamp
and $endTimestamp
).
What could be the cause for additional timers to break?