Good Day,
We are curently using the code snippet provided below to display a message on the front end of our website (i.e., contact page) indicating whether our business is open or not.
In order for the code snippet to work, we have to disable caching on our contact page.
Is there a way we can execute the code snippet provided below without disabling the caching of our contact page? Say, via another code snippet integrating a JS/ajax call? (see example below for basic framework).
We use Speed Optimizer (plugin) and Cloudflare APO to cache our site.
If you need more info, please ask 🙂
Thank you!
————————————
Code Snippet (Currently Using):
function business_hours_shortcode($atts) {
if (is_page ('contact')) {
// Set timezone - change this to match your own.
date_default_timezone_set('America/Chicago');// An array of your opening hours.
$opening_hours = array(
'Monday' => array('07:30', '17:30'),
'Tuesday' => array('07:30', '17:30'),
'Wednesday' => array('07:30', '17:30'),
'Thursday' => array('07:30', '17:30'),
'Friday' => array('07:30', '17:30'),
'Saturday' => array('Closed'),
'Sunday' => array('Closed'),
);
// An array of your holidays (format: month/day - add zero before single-digit month or day)
$holidays = array('01/01', '05/26', '07/04', '07/05', '09/02', '11/11', '11/28', '11/29', '12/24', '12/25', '12/31');
// Get current date, day, and time.
$current_date = date('m/d');
$current_day = date('l');
$current_time = date('H:i');
// Get today's opening hours.
$today_hours = $opening_hours[$current_day];
// Check if today is a holiday.
if (in_array($current_date,$holidays)) {
return '<span style="font-weight:600;color:#ffffff;background-color:#e14d43;opacity:.7;padding:6px 12px;border-radius:3px;">CLOSED FOR HOLIDAY</span>';
}
// Check if we have opening hours for today.
if (!isset($today_hours) || count($today_hours) < 2) {
return '<span style="font-weight:600;color:#ffffff;background-color:#e14d43;opacity:.7;padding:6px 12px;border-radius:3px;">CLOSED TODAY</span>';
}
// Check if current time is between opening hours.
if ($current_time >= $today_hours[0] && $current_time <= $today_hours[1]) {
return '<span style="font-weight:600;color:#ffffff;background-color:#00c853;opacity:.7;padding:6px 12px;border-radius:3px;">CURRENTLY OPEN</span>';
} else {
return '<span style="font-weight:600;color:#ffffff;background-color:#e14d43;opacity:.7;padding:6px 12px;border-radius:3px;">CURRENTLY CLOSED</span>';
}
}
}
add_shortcode('business_hours', 'business_hours_shortcode');
——————————
Code Snippet to Prevent Caching of PHP Code (Example, Not Tested):
function disable_business_hours_caching() {
if (! is_page('contact')) {
return;
}
?>
<script>
jQuery(document).ready(function($) {// insert code here //
$.ajax({
url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
// insert code here //
});
});
</script>
<?php
}
add_action('wp_footer', 'disable_business_hours_caching');