Issue Excluding Autoptimize From Caching
-
Good morning Frank. Thank you for your great plugin! Long time user here.
I am having a strange issue with your plugin (I believe), on two different sites, two unrelated issues. I will open a separate ticket for the second site :)
For this site, I have custom hours set to display in the header, with <!--noptimize--><!--/noptimize--> tags set, but the code is still being cached by Autoptimize for users not logged in, and instead of displaying the hours, it's displaying an error message 'Current hours unavailable'
If I disable the Autoptimize plugin, the code works correctly for both loggin and logged out users.
Can you see what I'm doing wrong? Thank you!
Here are my settings:
- Optimize JavaScript Code? (checked)
- Exclude scripts from Autoptimize:: admin-ajax.php, business-hours-ajax.js
- Optimize CSS Code? (checked)
- Optimize HTML Code? (checked)
- Enable configuration per post/ page? (checked)
Here is my PHP code which is setup as a plugin:
<?php
/*
Plugin Name: Custom Business Hours
Description: Displays dynamic business hours.
Version: 1.0
Author: Patrick
*/
function get_business_hours() {
date_default_timezone_set('America/New_York');
$current_day = date('l');
$current_time = date('H:i');
$hours = [
'Monday' => ['open' => '10:00', 'close' => '17:00'],
'Tuesday' => ['open' => '10:00', 'close' => '17:00'],
'Wednesday' => ['open' => '10:00', 'close' => '17:00'],
'Thursday' => ['open' => '10:00', 'close' => '17:00'],
'Friday' => ['open' => '10:00', 'close' => '16:00'],
'Saturday' => ['open' => '10:00', 'close' => '14:00'],
'Sunday' => null,
];
// Handle Saturday after 2 PM, all of Sunday, and Monday before opening
if (($current_day === 'Saturday' && $current_time >= '14:01') ||
$current_day === 'Sunday') {
return esc_html("CLOSED. OPENING MON AT 10 AM");
}
// Handle Monday early morning (12:01 AM to 9:59 AM)
if ($current_day === 'Monday' && $current_time >= '00:01' && $current_time < '10:00') {
return esc_html("CLOSED. OPENING AT 10 AM");
}
// Find next open day logic
$get_next_open_day = function() use ($hours, $current_day) {
$days_order = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
$current_index = array_search($current_day, $days_order);
for ($i = 1; $i <= 7; $i++) {
$next_index = ($current_index + $i) % 7;
$next_day = $days_order[$next_index];
if (isset($hours[$next_day]) && is_array($hours[$next_day])) {
$next_day_abbr = strtoupper(substr($next_day, 0, 3));
return [
'day' => $next_day_abbr,
'open' => date('gA', strtotime($hours[$next_day]['open']))
];
}
}
return null;
};
// Handle current day's business hours
if (isset($hours[$current_day]) && is_array($hours[$current_day])) {
$open = $hours[$current_day]['open'];
$close = $hours[$current_day]['close'];
if ($current_time < $open) {
$open_time = date('gA', strtotime($open));
return esc_html("CLOSED NOW. OPENING TODAY AT {$open_time}");
} elseif ($current_time <= $close) {
$open_time = date('gA', strtotime($open));
$close_time = date('gA', strtotime($close));
return esc_html("OPEN TODAY {$open_time}-{$close_time}");
} else {
$next = $get_next_open_day();
return esc_html("CLOSED NOW. OPENING {$next['day']} AT {$next['open']}");
}
}
return esc_html("CLOSED TODAY");
}
// Nonce handling for logged-out users
add_filter('nonce_user_logged_out', 'custom_nonce_uid', 10, 2);
function custom_nonce_uid($uid, $action) {
return ($action === 'business_hours_nonce') ? 0 : $uid;
}
// Shortcode with caching protection
function display_business_hours_shortcode() {
return '<!--noptimize--><div id="business-hours-container">Loading hours...</div><!--/noptimize-->';
}
add_shortcode('business_hours', 'display_business_hours_shortcode');
// AJAX handlers
add_action('wp_ajax_get_business_hours', 'business_hours_ajax_handler');
add_action('wp_ajax_nopriv_get_business_hours', 'business_hours_ajax_handler');
function business_hours_ajax_handler() {
if (!isset($_REQUEST['_wpnonce']) || !wp_verify_nonce($_REQUEST['_wpnonce'], 'business_hours_nonce')) {
status_header(403);
exit('Unauthorized request');
}
echo get_business_hours();
wp_die();
}
// Enqueue scripts with cache-busting
function enqueue_business_hours_scripts() {
wp_enqueue_script(
'business-hours-ajax',
plugins_url('js/business-hours-ajax.js', __FILE__),
[],
filemtime(plugin_dir_path(__FILE__) . 'js/business-hours-ajax.js'), // Cache-busting
true
);
wp_localize_script('business-hours-ajax', 'businessHoursAjax', [
'ajaxurl' => admin_url('admin-ajax.php'),
'_nonce' => wp_create_nonce('business_hours_nonce'),
]);
}
add_action('wp_enqueue_scripts', 'enqueue_business_hours_scripts');
Here's the script:
// business-hours-ajax.js
document.addEventListener("DOMContentLoaded", function () {
const container = document.getElementById("business-hours-container");
if (!container) return;
const retryFetch = (url, options, retries = 3) => {
return fetch(url, options)
.then(response => {
if (!response.ok) throw new Error('Network response not OK');
return response.text();
})
.catch(error => {
if (retries > 0) {
console.log(Retrying... attempts left: ${retries});
return new Promise(resolve => {
setTimeout(() => resolve(retryFetch(url, options, retries - 1)), 1000);
});
}
throw error;
});
};
container.innerHTML = '<span class="loading">Loading hours...</span>';
retryFetch(${businessHoursAjax.ajaxurl}?action=get_business_hours&_wpnonce=${businessHoursAjax._nonce}&t=${Date.now()})
.then(data => {
container.innerHTML = data;
})
.catch(error => {
console.error('Business hours error:', error);
container.innerHTML = '<span class="error">Current hours unavailable</span>';
});
});The page I need help with: [log in to see the link]
Viewing 8 replies - 1 through 8 (of 8 total)
Viewing 8 replies - 1 through 8 (of 8 total)
The topic ‘Issue Excluding Autoptimize From Caching’ is closed to new replies.