menu

Questions & Answers

Wordpress Buffer HTML Cache

I'm writing a plugin that writes the HTML output to the file and loads the site from that file, next time. It works flawlessly. But I can't cache the code after the wp_footer hook. I tried the "shutdown" hook that works after the wp_footer hook but it returns null. I don't know why it is returning null. But I need a hook that runs after the wp_footer hook, where I can cache all the code from 0 to 100.

<?php

$priority = 10;
add_action('template_redirect', function(){
    if(!is_admin() && !is_user_logged_in()){

        $cache_time = get_option('html_cache_time');
        if(empty($cache_time)){
            $cache_time = 60;
        }

        $current_url = get_site_url() . $_SERVER['REQUEST_URI'];

        if(filter_var($current_url, FILTER_SANITIZE_URL)){

            $parsed_url = parse_url($current_url);
            $url_path = isset($parsed_url['path']) ? $parsed_url['path'] : false;

            if(!empty($url_path)){

                $cached_url = NGY_CACHE_DIR . 'app/cached/' .  md5($url_path) . '.cache';

                define('NOGAY_CACHED_URL', $cached_url);
                $end_time = 60 * $cache_time;

                if(file_exists($cached_url)){
                    if(time() - $end_time < filemtime($cached_url)){
                        readfile($cached_url);
                        exit;
                    }else{
                        unlink($cached_url);
                    }
                }

            }
        }
        ob_start();
    }

}, $priority);

add_action('wp_footer', function(){
    if(!is_admin() && !is_user_logged_in()){

        $html = ob_get_clean();
        if(!file_exists(NOGAY_CACHED_URL)){
            echo $html;
        }

        $open_cached_file = fopen(NOGAY_CACHED_URL, 'w+');
        fwrite($open_cached_file, $html);
        fclose($open_cached_file);
        ob_end_flush();
    }
}, PHP_INT_MAX);

I tried another Wordpress hooks. (shutdown)

Answers(1) :

The shutdown hook may not be called in some cases, such as when the request is terminated prematurely due to a fatal error.

Use the send_headers hook, which is called after WordPress has finished processing the request and is ready to send the response headers back to the user, but before the response body is sent.

add_action('send_headers', function(){
    if(!is_admin() && !is_user_logged_in()){
        $html = ob_get_clean();
        if(!file_exists(NOGAY_CACHED_URL)){
            echo $html;
        }

        $open_cached_file = fopen(NOGAY_CACHED_URL, 'w+');
        fwrite($open_cached_file, $html);
        fclose($open_cached_file);
        ob_end_flush();
    }
}, PHP_INT_MAX);