Title: Issue Excluding Autoptimize From Caching
Last modified: April 9, 2025

---

# Issue Excluding Autoptimize From Caching

 *  Resolved [wpdv](https://wordpress.org/support/users/wpdv/)
 * (@wpdv)
 * [1 year ago](https://wordpress.org/support/topic/issue-excluding-autoptimize-from-caching/)
 *     ```wp-block-code
       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 HoursDescription: Displays dynamic business hours.Version: 1.0Author: 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 usersadd_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 protectionfunction display_business_hours_shortcode() {    return '<!--noptimize--><div id="business-hours-container">Loading hours...</div><!--/noptimize-->';}add_shortcode('business_hours', 'display_business_hours_shortcode');// AJAX handlersadd_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-bustingfunction 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.jsdocument.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>';        });});
       ```
   
    -  This topic was modified 1 year ago by [wpdv](https://wordpress.org/support/users/wpdv/).
 * The page I need help with: _[[log in](https://login.wordpress.org/?redirect_to=https%3A%2F%2Fwordpress.org%2Fsupport%2Ftopic%2Fissue-excluding-autoptimize-from-caching%2F%3Foutput_format%3Dmd&locale=en_US)
   to see the link]_

Viewing 8 replies - 1 through 8 (of 8 total)

 *  Plugin Author [Optimizing Matters](https://wordpress.org/support/users/optimizingmatters/)
 * (@optimizingmatters)
 * [1 year ago](https://wordpress.org/support/topic/issue-excluding-autoptimize-from-caching/#post-18408228)
 * there is no JS inside the noptimize-tags I’m afraid wpdv, just HTML, so noptimizing
   that is unlikely to help. does the problem go away when JS optimization if off?
 *  Thread Starter [wpdv](https://wordpress.org/support/users/wpdv/)
 * (@wpdv)
 * [1 year ago](https://wordpress.org/support/topic/issue-excluding-autoptimize-from-caching/#post-18408266)
 * I will test that. I’ve tried about everything I can think of over the past week
   trying to resolve, short of removing the plugin. I’ll report my findings. Thanks
 *  Plugin Author [Optimizing Matters](https://wordpress.org/support/users/optimizingmatters/)
 * (@optimizingmatters)
 * [1 year ago](https://wordpress.org/support/topic/issue-excluding-autoptimize-from-caching/#post-18408426)
 * disabling a AO (and plugins in general) triggers other things (caches being cleared
   left and right) so that does not provide conclusive proof. moreover typically-
   but not systematically- if the problem does not go away when disabling all AO
   options, the problem is not with AO to begin with 😉
 * if you can reproduce the problem on a staging site, I’ll be happy to have a look
   at what the frontend spits out (HTML/ JS/ browser console) to help you identify
   the root cause 🙂
 *  Thread Starter [wpdv](https://wordpress.org/support/users/wpdv/)
 * (@wpdv)
 * [1 year ago](https://wordpress.org/support/topic/issue-excluding-autoptimize-from-caching/#post-18408503)
 * Correct. However, with the AO plugin installed and only clearing the AO cache,
   the hours issue is resolves — until the next time it returns. So I’ve narrowed
   it down this far. Now I have only two AO setting checked: Optimize CSS Code? 
   and Optimize HTML Code?
    -  This reply was modified 1 year ago by [wpdv](https://wordpress.org/support/users/wpdv/).
 *  Plugin Author [Optimizing Matters](https://wordpress.org/support/users/optimizingmatters/)
 * (@optimizingmatters)
 * [1 year ago](https://wordpress.org/support/topic/issue-excluding-autoptimize-from-caching/#post-18408534)
 * well, that’s helpful; if something works and then it does not, it’s likely to
   be related to a nonce that is cached by a page cache (most of which get cleared
   when AO’s cache is cleared) and indeed in your PHP code I see a nonce being used.
   you will likely have to configure your page cache to consider a cached page invalid
   after 8 hours, that way the nonce will be refreshed in time 🙂
 *  Plugin Author [Optimizing Matters](https://wordpress.org/support/users/optimizingmatters/)
 * (@optimizingmatters)
 * [11 months ago](https://wordpress.org/support/topic/issue-excluding-autoptimize-from-caching/#post-18478591)
 * So were you able to fix this [@wpdv](https://wordpress.org/support/users/wpdv/)?
 *  Thread Starter [wpdv](https://wordpress.org/support/users/wpdv/)
 * (@wpdv)
 * [11 months ago](https://wordpress.org/support/topic/issue-excluding-autoptimize-from-caching/#post-18479684)
 * Frank,
 * I ended up removing the custom code, and the site with Autoptimize began working
   correctly again. Sorry for the trouble caused, as this is clearly on my end. 
   I did try making the changes suggested without luck. I’ve not had time to further
   troubleshoot. Thank you for your great product and support!
 *  Plugin Author [Optimizing Matters](https://wordpress.org/support/users/optimizingmatters/)
 * (@optimizingmatters)
 * [11 months ago](https://wordpress.org/support/topic/issue-excluding-autoptimize-from-caching/#post-18479883)
 * thanks for the feedback 🙂

Viewing 8 replies - 1 through 8 (of 8 total)

The topic ‘Issue Excluding Autoptimize From Caching’ is closed to new replies.

 * ![](https://ps.w.org/autoptimize/assets/icon-256X256.png?rev=2211608)
 * [Autoptimize](https://wordpress.org/plugins/autoptimize/)
 * [Frequently Asked Questions](https://wordpress.org/plugins/autoptimize/#faq)
 * [Support Threads](https://wordpress.org/support/plugin/autoptimize/)
 * [Active Topics](https://wordpress.org/support/plugin/autoptimize/active/)
 * [Unresolved Topics](https://wordpress.org/support/plugin/autoptimize/unresolved/)
 * [Reviews](https://wordpress.org/support/plugin/autoptimize/reviews/)

 * 8 replies
 * 2 participants
 * Last reply from: [Optimizing Matters](https://wordpress.org/support/users/optimizingmatters/)
 * Last activity: [11 months ago](https://wordpress.org/support/topic/issue-excluding-autoptimize-from-caching/#post-18479883)
 * Status: resolved